leetcode链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

题目

image.png

解答

深度遍历搜索:向下和向右搜索

  1. class Solution {
  2. public int movingCount(int m, int n, int k) {
  3. boolean[][] board = new boolean[m][n];
  4. return dfs(board, 0, 0, k);
  5. }
  6. private int dfs(boolean[][] board, int x, int y, int k) {
  7. // 终止条件:1.到达不可到的点 2.或者边界
  8. if (get(x) + get(y) > k || x >= board.length || y >= board[0].length || board[x][y]) {
  9. return 0;
  10. }
  11. board[x][y] = true;
  12. return dfs(board, x + 1, y, k) + dfs(board, x, y + 1, k) + 1;
  13. }
  14. private int get(int num) {
  15. int res = 0;
  16. while (num > 0) {
  17. res += num % 10;
  18. num /= 10;
  19. }
  20. return res;
  21. }
  22. }