130. Surrounded Regions

Posted 鸵鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了130. Surrounded Regions相关的知识,希望对你有一定的参考价值。

public class Solution {
    public void solve(char[][] board) {
    	if (board.length == 0 || board[0].length == 0)
    		return;
    	int m = board.length;
    	int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        
        for (int j = 0; j < n; j ++)
        {
        	if (board[0][j] == ‘O‘)
        		fill(0,j,board,visited);
        	if (board[m-1][j] == ‘O‘)
        		fill(m-1,j,board,visited);
        }
        
        for (int i = 0; i < m; i++)
        {
        	if (board[i][0] == ‘O‘)
        		fill(i,0,board,visited);
        	if (board[i][n-1] == ‘O‘)
        		fill(i,n-1,board,visited);
        }
        
        for (int i = 0; i < m; i++)
        	for (int j = 0; j < n; j++)
        		if (visited[i][j] == false&&board[i][j] == ‘O‘)
        			board[i][j] = ‘X‘;
    }

	private void fill(int i, int j, char[][] board, boolean[][] visited) {
		if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] == true || board[i][j] == ‘X‘)
			return;
		visited[i][j] = true;
		if(i > 1)
			fill(i-1,j,board,visited);
		if (i < board.length - 2)
			fill(i+1,j,board,visited);
		if (j > 1)
			fill(i,j-1,board,visited);
		if (j < board[0].length-2)
			fill(i,j+1,board,visited);
	}
}

  

以上是关于130. Surrounded Regions的主要内容,如果未能解决你的问题,请参考以下文章

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions