劍指offer:機器人的運動範圍
阿新 • • 發佈:2018-12-11
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
這種解法無法保證路徑是連通的:
public class Solution { private int numSum(int i) { int sum = 0; do{ sum += i%10; }while((i = i/10) > 0); return sum; } public int movingCount(int threshold, int rows, int cols) { int num = 0; for(int i = 0; i < rows;i++){ for(int j = 0; j < cols;j++){ if(numSum(i) + numSum(j) <=threshold) num++; } } return num; } }
解題思路:用變數 i j 的變化來描述路徑 (點的運動軌跡)
public class Solution { public int movingCount(int threshold, int rows, int cols) { int flag[][] = new int[rows][cols]; //記錄是否已經走過 return helper(0, 0, rows, cols, flag, threshold); } private int helper(int i, int j, int rows, int cols, int[][] flag, int threshold) { if (i < 0 || i >= rows || j < 0 || j >= cols || numSum(i) + numSum(j) > threshold || flag[i][j] == 1) return 0; flag[i][j] = 1; return helper(i - 1, j, rows, cols, flag, threshold) + helper(i + 1, j, rows, cols, flag, threshold) + helper(i, j - 1, rows, cols, flag, threshold) + helper(i, j + 1, rows, cols, flag, threshold) + 1; } private int numSum(int i) { int sum = 0; do{ sum += i%10; }while((i = i/10) > 0); return sum; } }
遞迴呼叫圖如下
用它的好處就是路線是連通的