Skip to content

Commit

Permalink
Merge pull request neetcode-gh#699 from arthurgarzajr/main
Browse files Browse the repository at this point in the history
Adding 130-Surrounded-Regions.swift
  • Loading branch information
Ahmad-A0 authored Aug 1, 2022
2 parents c756e82 + 86d9b39 commit f56b6d8
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions swift/130-Surrounded-Regions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
func solve(_ board: inout [[Character]]) {
var rows = board.count
var columns = board[0].count

// 1. DFS Capture unsurrounded regions (O -> T)
for r in 0..<rows {
for c in 0..<columns {
if board[r][c] == "O" &&
([0, rows - 1].contains(r) || [0, columns - 1].contains(c)) {
capture(r, c, &board)
}
}
}

// 2. Capture surrounded regions (O -> X)
for r in 0..<rows {
for c in 0..<columns {
if board[r][c] == "O" {
board[r][c] = Character("X")
}
}
}

// 3. Uncapture surrounded regions (T -> O)
for r in 0..<rows {
for c in 0..<columns {
if board[r][c] == "T" {
board[r][c] = Character("O")
}
}
}
}

func capture(_ r: Int, _ c: Int, _ board: inout [[Character]]) {
// Make sure r and c are in bounds
guard r >= 0, r < board.count, c >= 0, c < board[0].count, board[r][c] == "O" else {
return
}

board[r][c] = Character("T")

capture(r - 1, c, &board)
capture(r + 1, c, &board)
capture(r, c - 1, &board)
capture(r, c + 1, &board)
}
}

0 comments on commit f56b6d8

Please sign in to comment.