Description:
Given a char[][] graph, with character 'X' or 'O', we need to replace any 'O' with 'X' if 'O' is surrounded by 'O'.
Solution:
We may link all the 'O' regions and find that only those linked with the edge of char[][] will stay 'O', while others will become 'X', so we just need to find the 'O' linked with the edge part of char[][].
import java.util.LinkedList;
public class Solution {
int dir[][] = { { 1, -1, 0, 0 }, { 0, 0, 1, -1 } };
int n, m;
public void solve(char[][] board) {
n = board.length;
if (n == 0)
return;
m = board[0].length;
boolean vis[][] = new boolean[n][m];
LinkedList<node> queue = new LinkedList<node>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'O'
&& (i == 0 || i == n - 1 || j == 0 || j == m - 1)) {
queue.add(new node(i, j));
}
}
}
node temp;
int x, y, tx, ty;
while (!queue.isEmpty()) {
temp = queue.poll();
x = temp.x;
y = temp.y;
vis[x][y] = true;
for (int i = 0; i < 4; i++) {
tx = x + dir[0][i];
ty = y + dir[1][i];
if (valid(tx, ty) && !vis[tx][ty] && board[tx][ty] == 'O') {
queue.add(new node(tx, ty));
}
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (!vis[i][j])
board[i][j] = 'X';
}
boolean valid(int x, int y) {
if (x >= 0 && x < n && y >= 0 && y < m)
return true;
return false;
}
class node {
int x, y;
node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Solution s = new Solution();
char[][] map = new char[4][4];
map[0][1] = 'O';
s.solve(map);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
System.out.print(map[i][j] + " ");
System.out.println();
}
}
}