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排除不可以的节点,剩下的就是可以的节点了。

你可能感兴趣的:(round)