Java for LeetCode 130 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
解题思路:

对最外面一圈进行BFS,替换掉最外圈的连通范围,剩下的‘O’都是被包围的,就可以直接kill掉,JAVA实现如下:

	static public void solve(char[][] board) {
		if (board.length <= 2 || board[0].length <= 2)
			return;
		for (int row = 0; row < board.length; row++) {
			if (board[row][0] == 'O') {
				board[row][0] = 'T';
				bfs(board, row * board[0].length);
			}
			if (board[row][board[0].length - 1] == 'O') {
				board[row][board[0].length - 1] = 'T';
				bfs(board, row * board[0].length + board[0].length - 1);
			}
		}
		for (int col = 1; col < board[0].length - 1; col++) {
			if (board[0][col] == 'O') {
				board[0][col] = 'T';
				bfs(board, col);
			}
			if (board[board.length - 1][col] == 'O') {
				board[board.length - 1][col] = 'T';
				bfs(board, (board.length - 1) * board[0].length + col);
			}
		}
		for (int row = 0; row < board.length; row++)
			for (int col = 0; col < board[0].length; col++) {
				if (board[row][col] == 'T')
					board[row][col] = 'O';
				else if (board[row][col] == 'O')
					board[row][col] = 'X';
			}

	}

	static public void bfs(char[][] board, int num) {
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(num);
		while (!queue.isEmpty()) {
			num=queue.poll();
			int row = num / board[0].length;
			int col = num - row * board[0].length;
			if (row - 1 >= 0 && board[row - 1][col] == 'O') {
				board[row - 1][col] = 'T';
				queue.add(num - board[0].length);
			}
			if (row + 1 <= board.length - 1 && board[row + 1][col] == 'O') {
				board[row + 1][col] = 'T';
				queue.add(num + board[0].length);
			}
			if (col - 1 >= 0 && board[row][col - 1] == 'O') {
				board[row][col - 1] = 'T';
				queue.add(num - 1);
			}
			if (col + 1 <= board[0].length - 1 && board[row][col + 1] == 'O') {
				board[row][col + 1] = 'T';
				queue.add(num + 1);
			}
		}
	}

 

posted @ 2015-06-01 17:26  TonyLuis  阅读(275)  评论(0编辑  收藏  举报