Created
May 12, 2021 14:51
-
-
Save vrat28/6c4138004a004eeb52e4eac158e126f3 to your computer and use it in GitHub Desktop.
Range Sum 2D(Swift)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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