-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathContents.swift
79 lines (68 loc) · 2.2 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Foundation
struct Index: Hashable {
let row: Int
let column: Int
func right() -> Index {
return Index(row: row, column: column + 1)
}
func left() -> Index {
return Index(row: row, column: column - 1)
}
func bottom() -> Index {
return Index(row: row + 1, column: column)
}
func top() -> Index {
return Index(row: row - 1, column: column)
}
}
/*
This question was asked by Google.
Given an N by M matrix consisting only of 1's and 0's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
[[1, 0, 0, 0],
[1, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 0, 0]]
Return 4
*/
func largest(in matrix: [[Int]]) -> Int {
var visited = Set<Index>()
var max = 0
for row in 0 ..< matrix.count {
for column in 0 ..< matrix[row].count {
var rect = 0
largestHelper(index: Index(row: row, column: column), in: matrix, visited: &visited, count: &rect)
if rect > max { max = rect }
}
}
return max
}
func largestHelper(index: Index, in matrix: [[Int]], visited: inout Set<Index>, count: inout Int) {
if matrix[index.row][index.column] == 0
|| visited.contains(index) { return }
count += 1
visited.insert(index)
if withinBounds(index: index.right(), in: matrix) {
largestHelper(index: index.right(), in: matrix, visited: &visited, count: &count)
}
if withinBounds(index: index.left(), in: matrix) {
largestHelper(index: index.left(), in: matrix, visited: &visited, count: &count)
}
if withinBounds(index: index.top(), in: matrix) {
largestHelper(index: index.top(), in: matrix, visited: &visited, count: &count)
}
if withinBounds(index: index.bottom(), in: matrix) {
largestHelper(index: index.bottom(), in: matrix, visited: &visited, count: &count)
}
return
}
func withinBounds(index: Index, in matrix: [[Int]]) -> Bool {
return index.row < matrix.count
&& index.row >= 0
&& index.column < matrix[index.row].count
&& index.column >= 0
}
largest(in: [[1, 0, 0, 0],
[1, 0, 1, 1],
[1, 0, 1, 1],
[1, 0, 0, 0]])