被围绕的区域
题目
给一个二维的矩阵,包含 ‘X’ 和 ‘O’, 找到所有被 ‘X’ 围绕的区域,并用 ‘X’ 填充满。
样例
给出二维矩阵:
把被 ‘X’ 围绕的区域填充之后变为:
题解
public class Solution {
private static Queue<Integer> queue = null;
private static char[][] board;
private static int rows = 0;
private static int cols = 0;
/**
* @param board a 2D board containing 'X' and 'O'
* @return void
*/
public void surroundedRegions(char[][] board) {
if (board.length == 0 || board[0].length == 0)
{
return;
}
queue = new LinkedList<Integer>();
this.board = board;
rows = board.length;
cols = board[0].length;
for (int i = 0; i < rows; i++)
{
enqueue(i, 0);
enqueue(i, cols - 1);
}
for (int j = 1; j < cols - 1; j++)
{
enqueue(0, j);
enqueue(rows - 1, j);
}
while (!queue.isEmpty())
{
int cur = queue.poll();
int x = cur / cols;
int y = cur % cols;
if (board[x][y] == 'O')
{
board[x][y] = 'D';
}
enqueue(x - 1, y);
enqueue(x + 1, y);
enqueue(x, y - 1);
enqueue(x, y + 1);
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (board[i][j] == 'D')
{
board[i][j] = 'O';
}
else if (board[i][j] == 'O')
{
board[i][j] = 'X';
}
}
}
queue = null;
this.board = null;
rows = 0;
cols = 0;
}
public static void enqueue(int x, int y)
{
if (x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == 'O')
{
queue.offer(x * cols + y);
}
}
}
Last Update 2016.11.19