机器人运动的范围(BFS)

机器人运动的范围(BFS)

/*	剑指Offer13 机器人的运动范围
 * 	题目描述:地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。
 * 			一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),
 * 			  也不能进入行坐标和列坐标的数位之和大于k的格子。
 *  解题思路:
 *  		广度优先搜索,首先将00点入栈,然后将栈顶元素的可访问点入栈将栈顶元素出栈,直到栈空。
 * 
 * */
public class JiQiRenDeYunDongFanWei {
	public static void main(String[] args) {
		JiQiRenDeYunDongFanWei_Solution solution = new JiQiRenDeYunDongFanWei_Solution();
		System.out.println(solution.movingCount(3, 1, 0));
	}
}

class JiQiRenDeYunDongFanWei_Solution {
    public int movingCount(int m, int n, int k) {
    	//声明节果
    	int result = 0;
    	//创建map标记已被访问过的点
    	boolean[][] map = new boolean[m][n];
    	//声明栈
    	Stack<Integer[]> stack = new Stack<Integer[]>();
    	//将首元入栈
    	stack.push(new Integer[] {0,0});
    	result++;
    	map[0][0] = true;
    	while(stack.size()!=0) {
    		//将目标点出栈,上下左右四个方向的合法(下标不越界、未被访问过,不大于k)入栈
    		Integer[] temp = stack.pop();
    		int i = temp[0];
    		int j = temp[1];
    		if(j-1>=0 && toSum(i, j-1)<=k && map[i][j-1]==false) {
    			//up
    		//	System.out.println("up");
    			stack.push(new Integer[] {i,j-1});
    			map[i][j-1] = true;
    			result++;
    		}if(j+1<n && toSum(i, j+1)<=k && map[i][j+1]==false) {
    			//down
    		//	System.out.println("down");
    			stack.push(new Integer[] {i,j+1});
    			map[i][j+1] = true;
    			result++;
    		}if(i-1>=0 && toSum(i-1, j)<=k && map[i-1][j]==false) {
    			//left
    		//	System.out.println("left");
    			stack.push(new Integer[] {i-1,j});
    			map[i-1][j] = true;
    			result++;
    		}if(i+1<m && toSum(i+1, j)<=k && map[i+1][j]==false) {
    			//right
    		//	System.out.println("right");
    			stack.push(new Integer[] {i+1,j});
    			map[i+1][j] = true;
    			result++;
    		}
    	}
    	return result;
    }
    /* 输入两个介于1~100的int型数,要求返回这两个数按位拆开后的和
     * */
    public int toSum(int n,int m) {
    	String[] str_n = (n+"").split("");
    	String[] str_m = (m+"").split("");
    	int sum=0;
    	for (String string : str_n) {
			sum+=Integer.parseInt(string);
		}
    	for (String string : str_m) {
			sum+=Integer.parseInt(string);
		}
    	return sum;
    } 
}

猜你喜欢

转载自blog.csdn.net/zfr143816/article/details/107769868