let updateBoard = function(board, click) { let maxRow = board.length, maxCol = board[0].length, MINE = 'M', BLANK = 'B', EMPTY = 'E', GAMEOVER = 'X'; function isMine(row, col) { if (row < 0 || col < 0 || row >= maxRow || col >= maxCol) { return 0; } return board[row][col] === MINE ? 1 : 0; } function getMineCount(row, col) { let nearbyMines = 0; nearbyMines += isMine(row - 1, col - 1); // top left nearbyMines += isMine(row - 1, col); // top nearbyMines += isMine(row - 1, col + 1); // top right nearbyMines += isMine(row, col - 1); // left nearbyMines += isMine(row, col + 1); // right nearbyMines += isMine(row + 1, col - 1); // bottom left nearbyMines += isMine(row + 1, col); // bottom nearbyMines += isMine(row + 1, col + 1); // bottom right return nearbyMines; } function markAndExplore(row, col) { if (row < 0 || col < 0 || row >= maxRow || col >= maxCol) { return; } const data = board[row][col]; if (data === EMPTY) { const mineCount = getMineCount(row, col); board[row][col] = mineCount > 0 ? `${mineCount}` : BLANK; if (mineCount === 0) { markAndExplore(row - 1, col - 1); // top left markAndExplore(row - 1, col); // top markAndExplore(row - 1, col + 1); // top right markAndExplore(row, col - 1); // left markAndExplore(row, col + 1); // right markAndExplore(row + 1, col - 1); // bottom left markAndExplore(row + 1, col); // bottom markAndExplore(row + 1, col + 1); // bottom right } } } let [x, y] = click; if (board[x][y] === MINE) { board[x][y] = GAMEOVER; } else { markAndExplore(x, y); } return board; };
Categories