Surrounded Regions LeetCode :My Solution

Surrounded Regions

  Total Accepted: 14948  Total Submissions: 105121 My 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的位置的时候,不要弄错了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值