1. 程式人生 > 其它 >劍指 Offer 13. 機器人的運動範圍(BFS)

劍指 Offer 13. 機器人的運動範圍(BFS)

劍指 Offer 13. 機器人的運動範圍

地上有一個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 = 3, n = 1, k = 0
輸出:1

提示:

  • 1 <= n,m <= 100
  • 0 <= k <= 20
 1 class Solution {
 2 public:
 3     static constexpr int g_direction[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
 4     int getSingleSum(int x) {
 5         int sum = 0;
 6         while (x != 0) {
 7             sum += x % 10;
 8             x /= 10;
 9         }
10
return sum; 11 } 12 int getSinglePositionSum(int x, int y) { 13 return (getSingleSum(x) + getSingleSum(y)); 14 } 15 void buildGraph(int k, vector<vector<int>> &graph) { 16 if (graph.size() <= 0 || graph[0].size() <= 0) { 17 return
; 18 } 19 int row = graph.size(); 20 int cow = graph[0].size(); 21 for (int i = 0; i < row; i++) { 22 for (int j = 0; j < cow; j++) { 23 if (getSinglePositionSum(i, j) <= k) { 24 graph[i][j] = 1; 25 } 26 } 27 } 28 return; 29 } 30 int movingCount(int m, int n, int k) { 31 if (m <= 0 || n <= 0 || k < 0) { 32 return 0; 33 } 34 vector<vector<int>> graph(m, vector<int>(n, 0)); 35 // 構建機器人走的地圖 36 buildGraph(k, graph); 37 queue<std::pair<int, int>> q; // 儲存機器人可以走的方格座標 38 q.push(make_pair(0, 0)); // 原點位置可以走先入棧 39 graph[0][0] = 2; // 0-不可以走,1-可以走,2-已走過 40 int ans = 1; // 可以走的方格數,原點位置可以走,預設1個方格可以走 41 while (!q.empty()) { 42 int x = q.front().first; 43 int y = q.front().second; 44 q.pop(); 45 // 遍歷上、左、下、右四個方向,將可以走的方格座標入佇列 46 for (int i = 0; i < 4; i++) { 47 int xNext = x + g_direction[i][0]; 48 int yNext = y + g_direction[i][1]; 49 if ((xNext >= 0 && xNext < m) && (yNext >= 0 && yNext < n) && 50 (graph[xNext][yNext] == 1)) { 51 q.push(make_pair(xNext, yNext)); 52 graph[xNext][yNext] = 2; 53 ans++; 54 } 55 } 56 } 57 return ans; 58 } 59 };