【劍指Offer學習】【面試題67:機器人的運動範圍】
阿新 • • 發佈:2019-01-02
題目:地上有個m行n列的方格。一個機器人從座標(0,0)的格子開始移動,它每一次可以向左、右、上、下移動一格,但不能進入行座標和列座標的數位之和大於k的格子。
舉例分析
例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7=18.但它不能進入方格(35,38),因為3+5+3+8=19.請問該機器人能夠達到多少格子?
解題思路
和前面的【劍指Offer學習】【面試題66:矩陣中的路徑】類似,這個方格也可以看出一個m*n的矩陣。同樣在這個矩陣中,除邊界上的格子之外其他格子都有四個相鄰的格子。
機器人從座標(0,0)開始移動。當它準備進入座標為(i,j)的格子時,通過檢查座標的數位和來判斷機器人是否能夠進入。如果機器人能夠進入座標為(i,j)的格子,我們接著再判斷它能否進入四個相鄰的格子(i,j-1)、(i-1,j),(i,j+1)和(i+1,j)。
程式碼實現
public class Test67 {
/**
* 題目:地上有個m行n列的方格。一個機器人從座標(0,0)的格子開始移動,
* 它每一次可以向左、右、上、下移動一格,但不能進入行座標和列座標的數
* 位之和大於k的格子。例如,當k為18時,機器人能夠進入方格(35,37),
* 因為3+5+3+7=18.但它不能進入方格(35,38),因為3+5+3+8=19.
* 請問該機器人能夠達到多少格子?
*
* @param threshold 約束值
* @param rows 方格的行數
* @param cols 方格的列數
* @return 最多可走的方格
*/
public static int movingCount(int threshold, int rows, int cols) {
// 引數校驗
if (threshold < 0 || rows < 1 || cols < 1) {
return 0;
}
// 變數初始化
boolean[] visited = new boolean[rows * cols];
for (int i = 0; i < visited.length; i++) {
visited[i] = false;
}
return movingCountCore(threshold, rows, cols, 0, 0, visited);
}
/**
* 遞歸回溯方法
*
* @param threshold 約束值
* @param rows 方格的行數
* @param cols 方格的列數
* @param row 當前處理的行號
* @param col 當前處理的列號
* @param visited 訪問標記陣列
* @return 最多可走的方格
*/
private static int movingCountCore(int threshold, int rows, int cols,
int row, int col, boolean[] visited) {
int count = 0;
if (check(threshold, rows, cols, row, col, visited)) {
visited[row * cols + col] = true;
count = 1
+ movingCountCore(threshold, rows, cols, row - 1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col - 1, visited)
+ movingCountCore(threshold, rows, cols, row + 1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col + 1, visited);
}
return count;
}
/**
* 斷機器人能否進入座標為(row, col)的方格
*
* @param threshold 約束值
* @param rows 方格的行數
* @param cols 方格的列數
* @param row 當前處理的行號
* @param col 當前處理的列號
* @param visited 訪問標記陣列
* @return 是否可以進入,true是,false否
*/
private static boolean check(int threshold, int rows, int cols,
int row, int col, boolean[] visited) {
return col >= 0 && col < cols
&& row >= 0 && row < rows
&& !visited[row * cols + col]
&& (getDigitSum(col) + getDigitSum(row) <= threshold);
}
/**
* 一個數字的數位之和
*
* @param number 數字
* @return 數字的數位之和
*/
private static int getDigitSum(int number) {
int result = 0;
while (number > 0) {
result += (number % 10);
number /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println(movingCount(5, 10, 10) + "[21]");
System.out.println(movingCount(15, 20, 20) + "[359]");
System.out.println(movingCount(10, 1, 100) + "[29]");
System.out.println(movingCount(10, 1, 10) + "[10]");
System.out.println(movingCount(15, 100, 1) + "[79]");
System.out.println(movingCount(15, 10, 1) + "[10]");
System.out.println(movingCount(5, 10, 10) + "[21]");
System.out.println(movingCount(12, 1, 1) + "[1]");
System.out.println(movingCount(-10, 10, 10) + "[0]");
}
}