Set all of the O to – across the board
For each side find adjacent – and change them to Os using flash flood algorithm
Change all of the remaining – to X
The complexity of the above solution is O(m*n)
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function(board) {
for (let i=0; i< board.length; i++) {
for (let j=0; j< board[i].length; j++){
if (board[i][j] == 'O') {
board[i][j] = '-';
}
}
}
//left side
for (let i=0; i< board.length; i++) {
floodFill(board, i, 0, '-', 'O' );
}
//right side
for (let i=0; i< board.length; i++) {
floodFill(board, i, board[i].length-1, '-', 'O' );
}
//top side
for (let j=0; j< board[0].length; j++) {
floodFill(board, 0, j, '-', 'O' );
}
//bottom side
for (let j=0; j< board[0].length; j++) {
floodFill(board, board.length-1, j, '-', 'O' );
}
for (let i=0; i< board.length; i++) {
for (let j=0; j< board[i].length; j++){
if (board[i][j] == '-') {
board[i][j] = 'X';
}
}
}
return board;
};
var floodFill = function(board, i, j, prevVal, newVal) {
if (i<0 || j<0 || i>=board.length || j>=board[0].length) {
return;
}
if (prevVal != board[i][j]) {
return;
}
board[i][j] = newVal;
//check north
floodFill(board, i-1,j, prevVal, newVal);
//check east
floodFill(board, i,j+1, prevVal, newVal);
//check south
floodFill(board, i+1,j, prevVal, newVal);
//check west
floodFill(board, i,j-1, prevVal, newVal);
}