Thought: Any point that could not be reached if we started from four edges should be painted as 'X'.
Code:
public class Solution {
public void solve(char[][] board) {
int rows = board.length;
if (rows == 0) return;
int cols = board[0].length;
for (int j = 0; j < cols; j++) markFrom(board, 0, j);
for (int i = 0; i < rows; i++) markFrom(board, i, 0);
for (int j = 0; j < cols; j++) markFrom(board, rows - 1, j);
for (int i = 0; i < rows; i++) markFrom(board, i, cols - 1);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'M') board[i][j] = 'O';
else board[i][j] = 'X';
}
}
}
public void markFrom(char[][] board, int x, int y) {
int rows = board.length;
int cols = board[0].length;
if (x < 0 || x >= rows) return;
if (y < 0 || y >= cols) return;
if (board[x][y] == 'X' || board[x][y] == 'M') return;
board[x][y] = 'M';
markFrom(board, x - 1, y);
markFrom(board, x, y - 1);
markFrom(board, x + 1, y );
markFrom(board, x, y + 1);
}
}
No comments:
Post a Comment