您的位置:首页 > 其它

130. Surrounded Regions

2016-03-15 13:02 288 查看
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,
XXXX
XOOX
XXOX
XOXX
After running your function, the board should be:
XXXX
XXXX
XXXX
XOXX
Similar:286. Walls and Gates200. Number of Islands
 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;Queue<int[]> queue = new LinkedList<int[]>();
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') {
board[i][0] = 'H';
queue.offer(new int[] {i,0});
}
if (board[i][n-1] == 'O') {
board[i][n-1] = 'H';
queue.offer(new int[] {i,n-1});
}
}
for (int j = 1; j < n-1; j++) {
if (board[0][j] == 'O') {
board[0][j] = 'H';
queue.offer(new int[] {0,j});
}
if (board[m-1][j] == 'O') {
board[m-1][j] = 'H';
queue.offer(new int[] {m-1,j});
}
}int[] shift = {1, 0, -1, 0, 1};
while (!queue.isEmpty()) {
int[] pt = queue.poll();
for (int i=0; i<4; i++) {
int r = pt[0] + shift[i];
int c = pt[1] + shift[i+1];
if (r>=0 && r<m && c>=0 && c<n && board[r][c]=='O') {
board[r][c] = 'H';
queue.offer( new int[] {r,c});
}
}
}for (int i=0; i<m; i++)
for (int j=0; j<n ;j++) {
if (board[i][j] =='O') {
board[i][j] = 'X';
}
}
for (int i=0; i<m; i++)
for (int j=0; j<n; j++) {
if (board[i][j] == 'H') {
board[i][j] = 'O';
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: