130. Surrounding areas

Given a two-dimensional matrix, containing 'X' and 'o' (letter O).

Find all areas surrounded by 'X' and fill all 'O' in these areas with 'X'.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the matrix changes to:

X X X X
X X X X
X X X X
X O X X

Interpretation:

The enclosed interval does not exist on the boundary, in other words, 'O' on any boundary will not be filled with 'X'. Any 'O' that is not on or connected to the 'O' on the boundary will eventually be filled with 'X'. If two elements are adjacent horizontally or vertically, they are said to be "connected".

Solution idea: the original two-layer for loop intends to traverse, fails, and then looks up and finds that it is a more convenient method to start traversing around

class Solution {
    public void solve(char[][] board) {
        if(board==null||board.length<=1||board[0].length<=1)
            return;
        for(int i=0;i<board.length;i++)
        {
            if(board[i][0]=='O')
                dfs(board,i,0);
            if(board[i][board[0].length-1]=='O')
                dfs(board,i,board[0].length-1);
        }
        for(int j=0;j<board[0].length;j++)
        {
            if(board[0][j]=='O')
                dfs(board,0,j);
            if(board[board.length-1][j]=='O')
                dfs(board,board.length-1,j);
        }
        for(int i=0;i<board.length;i++)
        {
            for(int j=0;j<board[0].length;j++)
            {
                if(board[i][j]=='+')
                    board[i][j]='O';
                else if(board[i][j]=='O')
                    board[i][j]='X';
            }
        }
    }
    public void dfs(char[][]board,int row,int col)
    {
        if(row<0||row>=board.length||col<0||col>=board[0].length)
            return;
        if(board[row][col]!='O')
            return;
        board[row][col]='+';
        dfs(board,row+1,col);
        dfs(board,row,col+1);
        dfs(board,row-1,col); 
        dfs(board,row,col-1);
    }
}

 

Posted by validkeys on Wed, 01 Jan 2020 03:51:59 -0800