【劍指13】機器人的運動範圍
阿新 • • 發佈:2021-01-13
文章目錄
方法一:深度優先搜尋:時間O(mn),空間O(mn)
題解:
- 模擬機器人的走向,每次都先判斷能否到達目的位置,如果能到達,則標記該位置表示已經來過
- 機器人從左上角[0, 0]開始走,意味著 dfs 可以只向右和下走
class Solution {
public:
int res = 0;
bool isCorrect(int x, int y, int k)
{
int count = 0;
while (x || y)
{
if (x)
{
count += x % 10;
x /= 10;
}
if (y)
{
count += y % 10;
y /= 10;
}
}
return count <= k;
}
void movingboard(int m, int n, int k, int i, int j, vector<vector<bool>>& board)
{
if (i < 0 || i == m || j < 0 || j == n || board[i][j])
return;
// 先讓 board[i][j]為真,再去判斷該位置是否有效,如果該位置無效下次判斷該時,就省去了判斷位置函式的呼叫開銷
board[i][j] = true;
if (isCorrect(i, j, k))
{
res++;
// 優化:只需要向右和下走
movingboard(m, n, k, i + 1, j, board);
movingboard(m, n, k, i, j + 1, board);
}
}
int movingCount(int m, int n, int k)
{
vector<vector<bool>> board(m, vector<bool>(n, false));
movingboard(m, n, k, 0, 0, board);
return res;
}
};