• Surrounded Regions


    Surrounded Regions

    问题:

    Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.

    A region is captured by flipping all 'O's into 'X's in that surrounded region.

    思路:

      bfs

    我的代码:

    public class Solution {
        public void solve(char[][] board) {
            if(board==null || board.length==0 || board[0].length==0)    return;
            int row = board.length;
            int col = board[0].length;
            
            for(int i=0; i<row; i++)
            {
                fill(board, i, 0);
                fill(board, i, col-1);
            }
            for(int j=0; j<col; j++)
            {
                fill(board, 0, j);
                fill(board, row-1, j);
            }
            
            for(int i=0; i<row; i++)
            {
                for(int j=0; j<col; j++)
                {
                    if(board[i][j] == 'O')
                    {
                        board[i][j] = 'X';
                    }
                    else if(board[i][j] == '#')
                    {
                        board[i][j] = 'O';
                    }
                    
                }
            }
        }
        public void fill(char[][] board, int i, int j)
        {
            int row = board.length;
            int col = board[0].length;
            if(board[i][j] != 'O') return;
            board[i][j] = '#';
            LinkedList<Integer> queue = new LinkedList<Integer>();
            queue.offer(i*col + j);
            while(!queue.isEmpty())
            {
                int code = queue.poll();
                int r = code/col;
                int c = code%col;
                if(r>0 && board[r-1][c]=='O')
                {
                    queue.offer((r-1)*col+c);
                    board[r-1][c] = '#';
                }
                if(r<row-1 && board[r+1][c]=='O')
                {
                    queue.offer((r+1)*col+c);
                    board[r+1][c] = '#';
                }
                
                if(c<col-1 && board[r][c+1]=='O')
                {
                    queue.offer(r*col+(c+1));
                    board[r][c+1] = '#';
                }
                if(c>0 && board[r][c-1]=='O')
                {
                    queue.offer(r*col+(c-1));
                    board[r][c-1] = '#';
                }
            }
        }
    }
    View Code

    学习之处:

      一开始就想到bfs的思路,但是值想到了从哪个可以开始bfs,怎么就没有逆向思维,也可以通过bfs排除不可以的节点,剩下的就是可以的节点了。

  • 相关阅读:
    Tomcat系统架构分析
    org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
    Tomcat服务器的Web安全的解决方法
    在Tomcat中实现基本的HTTP方式的验证
    在Tomcat中采用基于表单的安全验证
    Tomcat对Struts中的Action进行授权利
    在 Tomcat 上配置虚拟主机
    在Tomcat中配置单点登录
    在Tomcat中配置连接池和数据源
    Tomcat常用操作
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4481130.html
Copyright © 2020-2023  润新知