[leetcode-130]Surrounded Regions(java)

问题描述:
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.

For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:

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

分析:这道题非常有意思,最开始我的想法是,从row = 1和col = 1的位置开始搜索,因为显然,最外层的O是不可能被包围的。可是后来一想,这样时间复杂度为O(N3)。而且也实在是太丑了。
接着想到,既然最外层的不会被包围,那如果最外层某个位置为O,那么紧挨着它的所有位置的O都不会被包围,因此,实际上是使用BFS的方法,利用一个队列的数据结构。
还有一点,在代码中,我新开辟了一个矩阵,visited,其实完全可以利用原来矩阵的信息存储。比如对于不会被包围的元素,将其变成P,这样当遇到P时,就将其恢复为O,否则为X。

代码如下:356ms

public class Solution {
    class Node{
        int row;
        int col;
        Node(int x,int y){
            row = x;col = y;
        }
    }
    public void solve(char[][] board) {
        int rowLen = board.length;
        if(rowLen<=0)
            return;
        int colLen = board[0].length;
        if(colLen<=0)
            return;


        int[][] visited = new int[rowLen][colLen];
        Queue queue = new LinkedList<>();

        for(int row = 0;rowfor(int col = 0;col0;

        for(int row = 0;rowif(board[row][0]=='O')
                queue.offer(new Node(row,0));
            if(board[row][colLen-1] == 'O')
                queue.offer(new Node(row,colLen-1));
        }
        for(int col = 0;colif(board[0][col]=='O')
                queue.offer(new Node(0,col));
            if(board[rowLen-1][col]=='O')
                queue.offer(new Node(rowLen-1,col));
        }
         while(!queue.isEmpty()){
                Node top = queue.poll();
                int rowrow = top.row;
                int colcol = top.col;
                if(visited[rowrow][colcol] == 1)
                    continue;

                visited[rowrow][colcol] = 1;

                if(rowrow+11][colcol] == 'O' && visited[rowrow+1][colcol] == 0)
                    queue.offer(new Node(rowrow+1,colcol));
                if(rowrow-1>=0 && board[rowrow-1][colcol] == 'O' && visited[rowrow-1][colcol] == 0)
                    queue.offer(new Node(rowrow-1,colcol));
                if(colcol+11] == 'O' && visited[rowrow][colcol+1] == 0)
                    queue.offer(new Node(rowrow,colcol+1));
                if(colcol-1>=0 && board[rowrow][colcol-1] == 'O' && visited[rowrow][colcol-1] == 0)
                    queue.offer(new Node(rowrow,colcol-1));
            }
        for(int row = 0;rowfor(int col = 0;colif(board[row][col] == 'O' && visited[row][col] == 0)
                    board[row][col] = 'X';
            }
        }
    }
}

你可能感兴趣的:(leetcode)