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
30 changes: 30 additions & 0 deletions lcof2/剑指 Offer II 013. 二维子矩阵的和/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,36 @@ class NumMatrix {
*/
```

#### Swift

```swift
class NumMatrix {
private var prefixSum: [[Int]]

init(_ matrix: [[Int]]) {
let m = matrix.count
let n = matrix[0].count
prefixSum = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)

for i in 1...m {
for j in 1...n {
prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1]
}
}
}

func sumRegion(_ row1: Int, _ col1: Int, _ row2: Int, _ col2: Int) -> Int {
return prefixSum[row2 + 1][col2 + 1] - prefixSum[row2 + 1][col1] - prefixSum[row1][col2 + 1] + prefixSum[row1][col1]
}
}

/**
* Your NumMatrix object will be instantiated and called as such:
* let obj = NumMatrix(matrix);
* let param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
25 changes: 25 additions & 0 deletions lcof2/剑指 Offer II 013. 二维子矩阵的和/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class NumMatrix {
private var prefixSum: [[Int]]

init(_ matrix: [[Int]]) {
let m = matrix.count
let n = matrix[0].count
prefixSum = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)

for i in 1...m {
for j in 1...n {
prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1]
}
}
}

func sumRegion(_ row1: Int, _ col1: Int, _ row2: Int, _ col2: Int) -> Int {
return prefixSum[row2 + 1][col2 + 1] - prefixSum[row2 + 1][col1] - prefixSum[row1][col2 + 1] + prefixSum[row1][col1]
}
}

/**
* Your NumMatrix object will be instantiated and called as such:
* let obj = NumMatrix(matrix);
* let param_1 = obj.sumRegion(row1,col1,row2,col2);
*/