《劍指offer》面試題13:矩陣中的路徑
題目:地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數(shù)位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
思路:回溯法:核心思路:
1.從(0,0)開始走,每成功走一步標記當前位置為true,然后從當前位置往四個方向探索,
返回1 + 4 個方向的探索值之和。
2.探索時,判斷當前節(jié)點是否可達的標準為:
1)當前節(jié)點在矩陣內(nèi);
2)當前節(jié)點未被訪問過;
3)當前節(jié)點滿足check(行坐標和列坐標的數(shù)位之和小于等于k)限制。
代碼如下:
public int movingCount(int threshold,int rows,int cols) {
boolean[] visited = new boolean[rows*cols];
return movingCountCore(threshold,rows,cols,0,0,visited);
}
private int movingCountCore(int threshold,int rows,int cols,int row,int col,boolean[] visited) {
int count = 0;
if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row * cols + col] && check(threshold,row,col)) {
visited[row * cols + col] = true;
count = 1 + movingCountCore(threshold,rows,cols,row + 1,col,visited) // 下
+ movingCountCore(threshold,rows,cols,row - 1,col,visited) // 上
+ movingCountCore(threshold,rows,cols,row,col + 1,visited) // 右
+ movingCountCore(threshold,rows,cols,row,col - 1,visited); // 左
}
return count;
}
private boolean check(int threshold,int row,int col) {
int sum = 0;
while (row != 0) {
sum += sum%row;
row = row/10;
}
while (col != 0) {
sum += sum%col;
col = col/10;
}
if (sum > threshold) {
return false;
}
return true;
}