https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/
我的方法一:广度优先搜索BFS
步骤
- state[m][n]代表一个点遍历的状态,0:未遍历,1:可以达到,2:不能到达
- 从(0, 0)开始广度优先搜索,使用一个队列q存储未遍历过的点,即状态是0的点
- 当搜索完后,计算1的点的数量
初始条件
state[m][n]全部初始化为0
边界条件
- m>0 && n>0& k>=0
- q先push(0,0)
- q当为空时,表示已经遍历完
复杂度
时间复杂度:O(MN)
空间复杂度:O(MN)
代码
class Solution {
public:
int movingCount(int m, int n, int k) {
if(m<=0 || n<=0 || k<0){
return 0;
}
int** state = new int* [m];
for(int i = 0; i< m; i++){
state[i] = new int[n];
for(int j=0; j<n; j++){
state[i][j] = 0;
}
}
pair<int, int> location = make_pair(0, 0);//row, col
queue<pair<int, int>> q;
q.push(location);
state[0][0] = 1;
int next_row = 0;
int next_col = 0;
while(!q.empty()){
location = q.front();
q.pop();
{
//left
next_row = location.first;
next_col = location.second - 1;
walk(m, n, k, next_row, next_col, state, q);
}
{
//right
next_row = location.first;
next_col = location.second + 1;
walk(m, n, k, next_row, next_col, state, q);
}
{
//top
next_row = location.first - 1;
next_col = location.second;
walk(m, n, k, next_row, next_col, state, q);
}
{
//bottom
next_row = location.first + 1;
next_col = location.second;
walk(m, n, k, next_row, next_col, state, q);
}
}
int count = 0;
for(int i = 0; i< m; i++){
for(int j=0; j<n; j++){
if(state[i][j] == 1){
count++;
}
}
}
return count;
}
inline void walk(int m, int n, int k, int next_row, int next_col, int** state, queue<pair<int, int>>& q){
if(next_row >= 0 && next_row<m && next_col>=0 && next_col<n){
if(state[next_row][next_col] == 0){
if((next_row/10 + next_row%10 + next_col/10 + next_col%10) <= k){
state[next_row][next_col] = 1;
q.push(make_pair(next_row, next_col));
}else{
state[next_row][next_col] = 2;
}
}
}
}
};
网友评论