-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1277.java
More file actions
68 lines (54 loc) · 1.67 KB
/
LC1277.java
File metadata and controls
68 lines (54 loc) · 1.67 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
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
/*
* LC1277
*/
import java.util.*;
public class LC1277 {
public static int countSquares(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
int ans = 0;
// For the firs row and column
for (int i = 1; i < m; i++) {
dp[0][i] = matrix[0][i];
ans += dp[0][i];
}
for (int i = 0; i < n; i++) {
dp[i][0] = matrix[i][0];
ans += dp[i][0];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (matrix[i][j] == 1) {
int left = dp[i][j - 1];
int top = dp[i - 1][j];
int topLeft = dp[i - 1][j - 1];
dp[i][j] = 1 + Math.min(Math.min(left, top), topLeft);
}
ans += dp[i][j];
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Row Size : ");
int row = sc.nextInt();
System.out.println();
System.out.print("Enter the Column Size : ");
int col = sc.nextInt();
System.out.println();
int[][] mat = new int[row][col];
System.out.println("Enter the Matrix elements : ");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.printf("[%d][%d] : ", i, j);
mat[i][j] = sc.nextInt();
}
}
System.out.println();
int ans = countSquares(mat);
System.out.println(ans);
sc.close();
}
}