请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

leetcode 130的DFS解法

bobo老师,我用DFS解决了lc 130 (https://leetcode.com/problems/surrounded-regions/) 问题。思路是先DFS遍历所有边界节点为'O'的字符,染色为true。最后简单遍历整个board, 把剩余的'O'重新赋值为'X' (代码如下)。成功提交后,我又回头看您的参考代码(https://github.com/liuyubobobo/Play-Leetcode/blob/master/0001-0500/0130-Surrounded-Regions/cpp-0130/main.cpp),您在文中说DFS可能会有问题,系统栈开销过大,所以用BFS。所以请教下,我的DFS成功提交,是不是说明DFS应该可行?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
    private boolean[][] visited;
    private final int[] dx = {10, -10};
    private final int[] dy = {010, -1};
    private char[][] board;
     
    public void solve(char[][] board) {
        this.board = board;
         
        int m = board.length;
        int n = board[0].length;
         
        visited = new boolean[m][n];
         
        for (int i = 0; i < m; i ++) {
            if (!visited[i][0] && board[i][0] == 'O'){
                dfs(i, 0);
            }
            if (!visited[i][n - 1] && board[i][n - 1] == 'O') {
                dfs(i, n - 1);
            }
        }
         
        for (int j = 0; j < n; j ++) {
            if (!visited[0][j] && board[0][j] == 'O') {
                dfs(0, j);
            }
            if (!visited[m - 1][j] && board[m - 1][j] == 'O') {
                dfs(m - 1, j);
            }
        }
         
        for (int i = 0; i < m; i ++) {
            for (int j = 0; j < n; j ++) {
                if (!visited[i][j] && board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
         
    }
     
    private void dfs(int x, int y) {
         
        visited[x][y] = true;
         
         
        for (int i = 0; i < 4; i ++) {
            int xx = x + dx[i];
            int yy = y + dy[i];
             
            if (inArea(xx, yy) && !visited[xx][yy] && board[xx][yy] == 'O') {
                dfs(xx, yy);
            }
        }
    }
     
    private boolean inArea(int x, int y) {
        return x >= 0 && x < board.length && y >= 0 && y < board[0].length;
    }
}


正在回答

插入代码

1回答

Leetcode 的 C++ 的编译环境有过升级,现在 dfs 是 ok 的。


继续加油!:)

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号