劍指 Offer 13. 機(jī)器人的運(yùn)動(dòng)范圍(dfs,bfs)

地上有一個(gè)m行n列的方格,從坐標(biāo) [0,0] 到坐標(biāo) [m-1,n-1] 。一個(gè)機(jī)器人從坐標(biāo) [0, 0] 的格子開(kāi)始移動(dòng),它每次可以向左、右、上、下移動(dòng)一格(不能移動(dòng)到方格外),也不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。例如,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格 [35, 37] ,因?yàn)?+5+3+7=18。但它不能進(jìn)入方格 [35, 38],因?yàn)?+5+3+8=19。請(qǐng)問(wèn)該機(jī)器人能夠到達(dá)多少個(gè)格子?

示例 1:
輸入:m = 2, n = 3, k = 1
輸出:3

示例 2:
輸入:m = 3, n = 1, k = 0
輸出:1

//dfs
class Solution {
    private int m;
    private int n;
    private int k;
    boolean[][] visited;
    public int movingCount(int m, int n, int k) {
        visited = new boolean[m][n];
        this.m = m;
        this.n = n;
        this.k = k;
        return dfs(0,0);
    }

    public int dfs(int x, int y){
        if(x >= m || y >= n || visited[x][y] || sum(x,y) > k){
            return 0;
        }
        visited[x][y] = true;
        return 1 + dfs(x+1,y) + dfs(x, y+1);
        // return 1 + dfs(x,y+1);
    }

    public int sum(int x,int y){
        int s = 0;
        while(x != 0){
            s += x % 10;
            x /= 10;
        }
        while(y != 0){
            s += y % 10;
            y /= 10;
        }
        return s;
    }
}
//bfs bfs 一般用隊(duì)列
class Solution {
    public int movingCount(int m, int n, int k) {
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[m][n];
        // int[] start = {0,0};
        queue.offer(new int[]{0,0});
        int count = 0;
        while(!queue.isEmpty()){
            int[] move = queue.poll();
            int x = move[0], y = move[1];
            if(x >= m || y >= n || sum(x,y) > k || visited[x][y]) continue;
            visited[x][y] = true;
            count++;
            queue.offer(new int[]{x+1,y});
            queue.offer(new int[]{x,y+1});
            // if(x+1 < m && y < n && !visited[x+1][y] && sum(x+1,y) <= k){
            //     queue.offer(new int[]{x+1,y});
            // }
            // if(x < m && y+1 < n && !visited[x][y+1] && sum(x,y+1) <= k){
            //     queue.offer(new int[]{x,y+1});
            // }
        }
        return count;
    }

    public int sum(int x, int y){
        int rs = 0;
        while(x>0){
            rs += x% 10;
            x /= 10;
        }
        while(y > 0){
            rs += y % 10;
            y /= 10;
        }
        return rs;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容