LeetCode: 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 .

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

思路:这里需要考虑的是被X包围的O,从四个边每个边开始遍历的话,进行深度遍历,只要是从 所有与四条边相连的O都保留,遍历四条边上的O,并深度遍历与其相连的O,将这些O都转为*,相当于是做了标记;

之后将剩余的O变为X,将剩余的*变为O,即可实现该替换。

完整代码:

public class SurroundRegion {
	public static void main(String[] args) {
		char[][] chars= {{'O','X','X','X','X'},{'O','X','O','O','X'},{'O','X','X','X','X'}};
		for(int i=0; i<chars.length; ++i) {
	          for(int j=0; j<chars[i].length; ++j)
	             System.out.print(chars[i][j]);
	          System.out.println('\n');
		}
		System.out.println("*************************");
		SurroundRegion sur=new SurroundRegion();
		sur.tihuan(chars);
		for(int i=0; i<chars.length; ++i) {
	          for(int j=0; j<chars[i].length; ++j)
	             System.out.print(chars[i][j]);
	          System.out.println('\n');//换行的显示
		}
	}
	
/*
* 所有与四条边相连的O都保留,其他O都变为X
* 遍历四条边上的O,并深度遍历与其相连的O,将这些O都转为*
* 将剩余的O变为X
* 将剩余的*变为O
*/
	public int rowNum = 0;
	public int colNum = 0;
	public void tihuan(char[][] board) {
		if(board == null || board.length <= 0|| board[0].length <= 0){
			 return;
	    }
		rowNum = board.length;
		//得到的是行数,直接数组名的长度的时候,就是高一级的数组的维度
		colNum = board[0].length;
		//得到的是列数
		System.out.println(colNum);
		//遍历了四条边对其进行深度遍历,只要是和边上的相连就不可以删除
		for(int i = 0; i < colNum; i++){
			dfs(board, 0, i);
			dfs(board, rowNum-1, i);
		}
		for(int i = 0; i < rowNum; i++){
			dfs(board, i, 0);
			dfs(board, i, colNum-1);
		}
		for(int i = 0; i < rowNum; i++){
			for(int j = 0; j < colNum; j++){
				if(board[i][j] == 'O'){
					board[i][j] = 'X';
				}
			}
		}
		for(int i = 0; i < rowNum; i++){
			for(int j = 0; j < colNum; j++){
			    if(board[i][j] == '*'){
			       board[i][j] = 'O';
			    }
			}
		}
	}
	private void dfs(char[][] board, int row, int col) {
			    // TODO Auto-generated method stub
		if(board[row][col] == 'O'){
			 board[row][col] = '*';
			 if(row > 1){
			     dfs(board, row-1, col);
			 }
			 if(col > 1){
			     dfs(board, row, col-1);
			 }
			 if(row < rowNum-1){
			     dfs(board, row+1, col);
			 }
			 if(col < colNum-1){
			      dfs(board, row, col+1);
			 }
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80222336
今日推荐