首页 > 其他 > 详细

Surrounded Regions LeetCode :My Solution

时间:2014-10-09 01:04:38      阅读:275      评论:0      收藏:0      [点我收藏+]

Surrounded Regions

 Total Accepted: 14948 Total Submissions: 105121My Submissions

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

Have you been asked this question in an interview? 



class Solution {
 	private static int rows = 0;
	private static int cols = 0;
	private static Queue<Integer> queue = null;
	private static char[][] myboard;

	public void solve(char[][] board) {
		if (board == null) {
			return;
		}
		if (board.length == 0 || board[0].length == 0) {
			return;
		}
		myboard = board;
		queue = new LinkedList<Integer>();
		rows = myboard.length;
		cols = myboard[0].length;
		for (int i = 0; i < rows; i++) {
			putQueue(0,i);
			putQueue(cols - 1,i);
		}
		for (int j = 1; j < cols - 1; j++) {
			putQueue(j,0);
			putQueue(j,rows - 1);
		}
		while (!queue.isEmpty()) {
			int position = queue.poll();
			int x = position % cols, y = position / cols;
			if (myboard[y][x] == 'O') {
				myboard[y][x] = 'D';
			}
			putQueue(x - 1, y);
			putQueue(x + 1, y);
			putQueue(x, y - 1);
			putQueue(x, y + 1);

		}
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (myboard[i][j] == 'O') {
					myboard[i][j] = 'X';
				} else if (myboard[i][j] == 'D') {
					myboard[i][j] = 'O';
				}
			}
		}

	}

	public void putQueue(int x, int y) {
		if (0 <= x && x < cols && 0 <= y && y < rows && myboard[y][x] == 'O') {
			queue.offer(y * cols + x);
		}
	}
}

这个题目,有个东西 那个是O 而不是0!!!!!!!!!!。。。。。

另外计算xy的位置的时候,不要弄错了

Surrounded Regions LeetCode :My Solution

原文:http://blog.csdn.net/aresgod/article/details/39901747

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!