机器人的运动范围
考察知识点:BFS、DFS
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例1:
输入:m = 2, n = 3, k = 1
输出:3
示例2:
输入:m = 1, n = 1, k = 0
输出:1
#include <iostream> using namespace std; #include<vector> #include<queue> class Solution { public: int movingCount(int m, int n, int k) { vector<vector<bool>> visted(m, vector<bool>(n, false)); int res = 0; queue<pair<int, int>> c; if (0 <= k) { c.push({0, 0}); res += 1; visted[0][0] = true; } while (!c.empty()) { pair<int, int> temp = c.front(); c.pop(); if (((temp.first + 1) <= (m - 1)) && (!visted[temp.first + 1][temp.second]) && ((getbit(temp.first + 1) + getbit(temp.second)) <= k)) { res += 1; visted[temp.first + 1][temp.second] = true; c.push({temp.first + 1, temp.second}); } if (((temp.second + 1) <= (n - 1)) && (!visted[temp.first][temp.second + 1]) && ((getbit(temp.first) + getbit(temp.second + 1)) <= k)) { res += 1; visted[temp.first][temp.second + 1] = true; c.push({temp.first, temp.second + 1}); } } return res; } int getbit(int i) { int res = 0; do { res += (i % 10); i /= 10; } while (i != 0); return res; } }; int main() { Solution s; cout << s.movingCount(3, 19, 10); }
浙公网安备 33010602011771号