剑指 Offer 13. 机器人的运动范围

public int movingCount(int m, int n, int k) {  //暴力法?
        boolean[][] visited = new boolean[m][n];
        return move_count(m,n,k,0,0,visited);
    }

    private int move_count(int m, int n, int k, int row_start,int col_start, boolean[][] visited) {
        if(row_start<0 || row_start ==m || col_start<0 || col_start == n) return 0;
        if(!visited[row_start][col_start]) {
            visited[row_start][col_start] = true;
            int h = 0;
            int x = row_start, y = col_start;
            while (x >= 10) {
                h += x % 10;
                x = x / 10;
            }
            while (y >= 10) {
                h += y % 10;
                y = y / 10;
            }
            h = h + x + y;
            if (h <= k) {
                return 1+ move_count(m, n, k, row_start + 1, col_start, visited)
                        + move_count(m, n, k, row_start - 1, col_start,visited)
                        +move_count(m, n, k, row_start, col_start + 1, visited)
                        +move_count(m, n, k, row_start, col_start - 1,  visited);
            }
        }
        return 0;
    }

 

 深度优先遍历,递归

posted @ 2020-08-08 15:20  欣姐姐  阅读(155)  评论(0编辑  收藏  举报