BFS和DFS的应用

本文深入解析了LeetCode上的两道经典算法题:被围绕的区域与对称二叉树,详细介绍了如何通过DFS和队列实现解决方案,帮助读者理解并掌握算法背后的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

130. 被围绕的区域

https://leetcode-cn.com/problems/surrounded-regions/

    public void solve(char[][] board) {
        if (board.length < 3 || board[0].length < 3) {
            return;
        }
        //以边界节点为根执行dfs,符合条件的O标记为F
        for (int i = 0; i < board[0].length; i++) {
            //遍历上边
            dfs(board, 0, i);
        }
        for (int i = 0; i < board[0].length; i++) {
            //遍历下边
            dfs(board, board.length-1, i);
        }
        for (int i = 1; i < board.length-1; i++) {
            //遍历左边
            dfs(board, i, 0);
        }
        for (int i = 1; i < board.length-1; i++) {
            //遍历右边
            dfs(board, i, board[0].length-1);
        }

        //处理标记节点和其他节点
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == 'F') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void dfs(char[][] board, int x, int y) {
        if (x < 0 || y < 0 || x > board.length - 1 || y > board[0].length - 1) {
            return;
        }
        if (board[x][y] == 'X' || board[x][y] == 'F') {
            //无需处理或者已经处理过
            return;
        } else {
            board[x][y] = 'F';
        }

        //处理邻居
        dfs(board, x - 1, y);
        dfs(board, x, y-1);
        dfs(board, x+1, y);
        dfs(board, x, y+1);
    }

101. 对称二叉树

https://leetcode-cn.com/problems/symmetric-tree/

    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode t1 = queue.poll();
            TreeNode t2 = queue.poll();
            if (t1 == null && t2 == null) {
                continue;
            }
            if (t1 == null || t2 == null) {
                return false;
            }
            if (t1.val != t2.val) {
                return false;
            }
            queue.offer(t1.left);
            queue.offer(t2.right);
            queue.offer(t1.right);
            queue.offer(t2.left);
        }
        return true;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值