/**
* Starting from four borders, if we meet an 'O' do the BFS on this point.
* We need to check if the coordiantes of its neighbors are valid (i.e. inside the board) and all the value of neighbors is 'O' as well.
* Mark all 'O' with 'M'.
* Finally, mark all 'O' with 'X' and 'M' with 'O'.
*/
public class Solution {
public void solve(char[][] board) {
if (board.length == 0) {
return;
}
int row = board.length;
int col = board[0].length;
// check all four borders and mark all 'O' with 'M'
// top border
for (int i=0; i<col; i++) {
if (board[0][i] == 'O') {
bfs(board, 0, i);
}
}
// bottom border
for (int i=0; i<col; i++) {
if (board[row-1][i] == 'O') {
bfs(board, row-1, i);
}
}
// left border
for (int i=0; i<row; i++) {
if (board[i][0] == 'O') {
bfs(board, i, 0);
}
}
// right border
for (int i=0; i<row; i++) {
if (board[i][col-1] == 'O') {
bfs(board, i, col-1);
}
}
// scan the whole board and replace all 'M' with X, all 'O' with X
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == 'M') {
board[i][j] = 'O';
}
}
}
}
private static class Coordinate {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
private static void bfs(char[][] board, int i, int j) {
// starting from [i, j] search all neighbors using BFS, mark all 'O' as 'M'
Queue<Coordinate> queue = new LinkedList<>();
HashSet<Coordinate> set = new HashSet<>();
Coordinate start = new Coordinate(i, j);
queue.offer(start);
set.add(start);
board[i][j] = 'M';
while (!queue.isEmpty()) {
Coordinate node = queue.poll();
for (Coordinate neighbor : getNeighbors(node, board)) {
if (set.add(neighbor)) {
queue.offer(neighbor);
}
}
}
}
private static List<Coordinate> getNeighbors(Coordinate node, char[][] board) {
List<Coordinate> neighbors = new ArrayList<>();
// check if the surrounding nodes are valid,
// i.e. a valid node would be the value is 'O' and it is in the borad
int row = board.length;
int col = board[0].length;
int i = node.x;
int j = node.y;
// check top side
if (i-1 >= 0 && board[i-1][j] == 'O') {
neighbors.add(new Coordinate(i-1, j));
board[i-1][j] = 'M';
}
// check bottom side
if (i+1 < row && board[i+1][j] == 'O') {
neighbors.add(new Coordinate(i+1, j));
board[i+1][j] = 'M';
}
// check left side
if (j-1 >= 0 && board[i][j-1] == 'O') {
neighbors.add(new Coordinate(i, j-1));
board[i][j-1] = 'M';
}
// check right side
if (j+1 < col && board[i][j+1] == 'O') {
neighbors.add(new Coordinate(i, j+1));
board[i][j+1] = 'M';
}
return neighbors;
}
}
Leetcode 130. Surrounded Regions
最新推荐文章于 2022-12-03 18:28:45 发布