Created
August 20, 2021 01:38
-
-
Save ifndefdeadmau5/2ce86880165cbd1cbabebbe4e371d61c to your computer and use it in GitHub Desktop.
leetcode medium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Coordinate = [number, number]; | |
function updateBoard(board: string[][], click: number[]): string[][] { | |
const boardCopy = [...board]; | |
const coordinates: Coordinate = [click[0], click[1]]; | |
const result = traverse(boardCopy, coordinates); | |
return result; | |
}; | |
const traverse = ( | |
board: string[][], | |
coordinates: Coordinate, | |
) => { | |
if (!validateCoord(coordinates, board.length, board[0].length)) return board; | |
const [x, y] = coordinates; | |
if (board[x][y] === "B") { return board; } | |
console.log(`traversing ${x}, ${y}...`); | |
if (board[x][y] === "M") { | |
board[x][y] = "X"; | |
return board; | |
} | |
const count = countAdjacentMines(board, [x, y]); | |
if (count) { | |
board[x][y] = String(count); | |
return board; | |
} | |
board[x][y] = 'B'; | |
traverse(board, [x - 1, y]); | |
traverse(board, [x - 1, y + 1]); | |
traverse(board, [x, y + 1]); | |
traverse(board, [x + 1, y + 1]); | |
traverse(board, [x + 1, y]); | |
traverse(board, [x + 1, y - 1]); | |
traverse(board, [x, y - 1]); | |
traverse(board, [x - 1, y - 1]); | |
return board; | |
}; | |
const countAdjacentMines = (board: string[][], coord: [number, number]) => { | |
const [x, y] = coord; | |
let count = 0; | |
if (board[x - 1]?.[y - 1] === "M") count += 1; | |
if (board[x - 1]?.[y] === "M") count += 1; | |
if (board[x - 1]?.[y + 1] === "M") count += 1; | |
if (board[x]?.[y - 1] === "M") count += 1; | |
if (board[x]?.[y] === "M") count += 1; | |
if (board[x]?.[y + 1] === "M") count += 1; | |
if (board[x + 1]?.[y - 1] === "M") count += 1; | |
if (board[x + 1]?.[y] === "M") count += 1; | |
if (board[x + 1]?.[y + 1] === "M") count += 1; | |
return count; | |
}; | |
const validateCoord = (coords: Coordinate, maxX: number, maxY: number) => { | |
const [x, y] = coords; | |
if (x >= 0 && x < maxX && y >= 0 && y < maxY) return true; | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment