Skip to content

Instantly share code, notes, and snippets.

@ValeriiVasin
Created June 17, 2020 13:57
Show Gist options
  • Save ValeriiVasin/ebade0b74fe2241341c7c688d7aa6643 to your computer and use it in GitHub Desktop.
Save ValeriiVasin/ebade0b74fe2241341c7c688d7aa6643 to your computer and use it in GitHub Desktop.
const O = 'O';
const X = 'X';
const T = 'T';
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function(board) {
if (board.length < 2 || board[0].length < 2) {
return;
}
for (let [x, y] of findBoundaryZeros(board)) {
fillZeroRegion(board, x, y);
}
for (let y = 0; y < board.length; y++) {
for (let x = 0; x < board[0].length; x++) {
const value = board[y][x];
if (value === X) {
continue;
}
if (value === T) {
board[y][x] = O;
continue;
}
board[y][x] = X;
}
}
};
function findBoundaryZeros(board) {
const result = [];
const yMin = 0;
const yMax = board.length - 1;
const xMin = 0;
const xMax = board[0].length - 1;
for (let x = 0; x <= xMax; x++) {
if (board[yMin][x] === O) {
result.push([x, yMin]);
}
if (board[yMax][x] === O) {
result.push([x, yMax]);
}
}
for (let y = 0; y <= yMax; y++) {
if (board[y][xMin] === O) {
result.push([xMin, y]);
}
if (board[y][xMax] === O) {
result.push([xMax, y]);
}
}
return result;
}
function fillZeroRegion(board, x, y) {
if (!checkBoundaries(board, x, y)) {
return;
}
if (board[y][x] !== O) {
return;
}
board[y][x] = T;
fillZeroRegion(board, x - 1, y);
fillZeroRegion(board, x + 1, y);
fillZeroRegion(board, x, y - 1);
fillZeroRegion(board, x, y + 1);
}
function checkBoundaries(board, x, y) {
if (y < 0 || y >= board.length) {
return false;
}
if (x < 0 || x >= board[0].length) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment