1. 程式人生 > >劍指offer-66:機器人的運動範圍

劍指offer-66:機器人的運動範圍

題目描述

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

思路

回溯法
核心思路:
1.從(0,0)開始走,每成功走一步標記當前位置為true,然後從當前位置往四個方向探索,
返回1 + 4 個方向的探索值之和。
2.探索時,判斷當前節點是否可達的標準為:
1)當前節點在矩陣內;
2)當前節點未被訪問過;
3)當前節點滿足limit限制。

程式碼

public class Solution66 {

    public int movingCount(int threshold, int rows, int cols) {
        boolean[][] visited = new boolean[rows][cols];
        return countingSteps(threshold, rows, cols, 0, 0, visited);
    }

    public int countingSteps(int limit, int rows, int cols, int r, int c,
boolean[][] visited) { if (r < 0 || r >= rows || c < 0 || c >= cols || visited[r][c] || bitSum(r) + bitSum(c) > limit) return 0; visited[r][c] = true; return countingSteps(limit, rows, cols, r - 1, c, visited) + countingSteps(limit,
rows, cols, r, c - 1, visited) + countingSteps(limit, rows, cols, r + 1, c, visited) + countingSteps(limit, rows, cols, r, c + 1, visited) + 1; } public int bitSum(int t) { int count = 0; while (t != 0) { count += t % 10; t /= 10; } return count; } public static void main(String[] args) { BeanUtil.print(new Solution66().movingCount(18,100,100)); } }