-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCount_SqSubMatrices.java
More file actions
37 lines (31 loc) · 1.09 KB
/
Count_SqSubMatrices.java
File metadata and controls
37 lines (31 loc) · 1.09 KB
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
class Solution {
public int countSquares(int[][] matrix) {
// Get dimensions of the matrix
int n = matrix.length; // number of rows
int m = matrix[0].length; // number of columns
// Create a DP table with same dimensions as matrix
int[][] dp = new int[n][m];
// Variable to store total count of squares
int ans = 0;
// Initialize first column of DP table
for (int i = 0; i < n; i++) {
dp[i][0] = matrix[i][0];
ans += dp[i][0];
}
// Initialize first row of DP table
for (int j = 1; j < m; j++) {
dp[0][j] = matrix[0][j];
ans += dp[0][j];
}
// Fill the DP table for remaining cells
for(int i = 1; i < n; i++) {
for(int j = 1; j < m; j++) {
if(matrix[i][j] == 1) {
dp[i][j] = 1 + Math.min(Math.min(dp[i][j-1], dp[i-1][j]), dp[i-1][j-1]);
}
ans += dp[i][j];
}
}
return ans;
}
}