Skip to content

Instantly share code, notes, and snippets.

@congnd
Created February 21, 2020 00:20
Show Gist options
  • Save congnd/c06b061585bd16002823b9051fff4872 to your computer and use it in GitHub Desktop.
Save congnd/c06b061585bd16002823b9051fff4872 to your computer and use it in GitHub Desktop.
Swift solution for minesweeper challenge: https://leetcode.com/problems/minesweeper
class Solution {
func updateBoard(_ board: [[Character]], _ click: [Int]) -> [[Character]] {
let h = board.count
let w = board[0].count
var copied = board
func checkAdjacentPoints(x: Int, y: Int) {
var numberOfBombs = 0
for i in max(0,x-1)...min(h-1,x+1) {
for j in max(0,y-1)...min(w-1,y+1) {
if i==x, j==y { continue }
if copied[i][j] == "M" { numberOfBombs += 1 }
}
}
if numberOfBombs == 0 {
copied[x][y] = "B"
for i in max(0,x-1)...min(h-1,x+1) {
for j in max(0,y-1)...min(w-1,y+1) {
if i==x, j==y { continue }
if copied[i][j] == "E" { checkAdjacentPoints(x: i, y: j) }
}
}
} else {
copied[x][y] = Character("\(numberOfBombs)")
}
}
if copied[click[0]][click[1]] == "M" {
copied[click[0]][click[1]] = "X"
} else {
checkAdjacentPoints(x: click[0], y: click[1])
}
return copied
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment