Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions lcci/16.04.Tic-Tac-Toe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,41 @@ function tictactoe(board: string[]): string {
return hasEmptyGrid ? 'Pending' : 'Draw';
}
```
```swift
class Solution {
func tictactoe(_ board: [String]) -> String {
let n = board.count
var rows = Array(repeating: 0, count: n)
var cols = Array(repeating: 0, count: n)
var diagonal = 0, antiDiagonal = 0
var hasEmptyGrid = false

for i in 0..<n {
for j in 0..<n {
let c = Array(board[i])[j]
if c == " " {
hasEmptyGrid = true
continue
}
let value = c == "X" ? 1 : -1
rows[i] += value
cols[j] += value
if i == j {
diagonal += value
}
if i + j == n - 1 {
antiDiagonal += value
}
if abs(rows[i]) == n || abs(cols[j]) == n || abs(diagonal) == n || abs(antiDiagonal) == n {
return String(c)
}
}
}

return hasEmptyGrid ? "Pending" : "Draw"
}
}
```

<!-- tabs:end -->

Expand Down
36 changes: 36 additions & 0 deletions lcci/16.04.Tic-Tac-Toe/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,42 @@ function tictactoe(board: string[]): string {
}
```

```swift
class Solution {
func tictactoe(_ board: [String]) -> String {
let n = board.count
var rows = Array(repeating: 0, count: n)
var cols = Array(repeating: 0, count: n)
var diagonal = 0, antiDiagonal = 0
var hasEmptyGrid = false

for i in 0..<n {
for j in 0..<n {
let c = Array(board[i])[j]
if c == " " {
hasEmptyGrid = true
continue
}
let value = c == "X" ? 1 : -1
rows[i] += value
cols[j] += value
if i == j {
diagonal += value
}
if i + j == n - 1 {
antiDiagonal += value
}
if abs(rows[i]) == n || abs(cols[j]) == n || abs(diagonal) == n || abs(antiDiagonal) == n {
return String(c)
}
}
}

return hasEmptyGrid ? "Pending" : "Draw"
}
}
```

<!-- tabs:end -->

<!-- end -->
33 changes: 33 additions & 0 deletions lcci/16.04.Tic-Tac-Toe/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
func tictactoe(_ board: [String]) -> String {
let n = board.count
var rows = Array(repeating: 0, count: n)
var cols = Array(repeating: 0, count: n)
var diagonal = 0, antiDiagonal = 0
var hasEmptyGrid = false

for i in 0..<n {
for j in 0..<n {
let c = Array(board[i])[j]
if c == " " {
hasEmptyGrid = true
continue
}
let value = c == "X" ? 1 : -1
rows[i] += value
cols[j] += value
if i == j {
diagonal += value
}
if i + j == n - 1 {
antiDiagonal += value
}
if abs(rows[i]) == n || abs(cols[j]) == n || abs(diagonal) == n || abs(antiDiagonal) == n {
return String(c)
}
}
}

return hasEmptyGrid ? "Pending" : "Draw"
}
}