Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 12, 2021 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/6c4138004a004eeb52e4eac158e126f3 to your computer and use it in GitHub Desktop.
Save vrat28/6c4138004a004eeb52e4eac158e126f3 to your computer and use it in GitHub Desktop.
Range Sum 2D(Swift)
class NumMatrix {
var dp : [[Int]]
init(_ matrix: [[Int]]) {
let r = matrix.count , c = matrix[0].count
dp = Array(repeating: Array(repeating:0,count:c + 1), count:r + 1)
for i in 1...r {
for j in 1...c{
dp[i][j] += matrix[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]
}
}
}
func sumRegion(_ row1: Int, _ col1: Int, _ row2: Int, _ col2: Int) -> Int {
return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment