Skip to content

Commit 7fbd48f

Browse files
committed
Add Largest Square in a Matrix
1 parent 38a1997 commit 7fbd48f

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
fun largestSquareInAMatrix(matrix: List<List<Int>>): Int {
2+
if (matrix.isEmpty()) {
3+
return 0
4+
}
5+
val m = matrix.size
6+
val n = matrix[0].size
7+
val dp = Array(m) { IntArray(n) }
8+
var maxLen = 0
9+
// Base case: If a cell in row 0 is 1, the largest square ending there has a
10+
// length of 1.
11+
for (j in 0 until n) {
12+
if (matrix[0][j] == 1) {
13+
dp[0][j] = 1
14+
maxLen = 1
15+
}
16+
}
17+
// Base case: If a cell in column 0 is 1, the largest square ending there has
18+
// a length of 1.
19+
for (i in 0 until m) {
20+
if (matrix[i][0] == 1) {
21+
dp[i][0] = 1
22+
maxLen = 1
23+
}
24+
}
25+
// Populate the rest of the DP table.
26+
for (i in 1 until m) {
27+
for (j in 1 until n) {
28+
if (matrix[i][j] == 1) {
29+
// The length of the largest square ending here is determined by
30+
// the smallest square ending at the neighboring cells (left,
31+
// top-left, top), plus 1 to include this cell.
32+
dp[i][j] = 1 + minOf(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1])
33+
}
34+
maxLen = maxOf(maxLen, dp[i][j])
35+
}
36+
}
37+
return maxLen * maxLen
38+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
fun largestSquareInAMatrixOptimized(matrix: Array<IntArray>): Int {
2+
if (matrix.isEmpty()) return 0
3+
val m = matrix.size
4+
val n = matrix[0].size
5+
var prevRow = IntArray(n)
6+
var maxLen = 0
7+
// Iterate through the matrix.
8+
for (i in 0 until m) {
9+
val currRow = IntArray(n)
10+
for (j in 0 until n) {
11+
// Base cases: if we’re in row 0 or column 0, the largest square ending
12+
// here has a length of 1. This can be set by using the value in the
13+
// input matrix.
14+
if (i == 0 || j == 0) {
15+
currRow[j] = matrix[i][j]
16+
} else {
17+
if (matrix[i][j] == 1) {
18+
// curr_row[j] = 1 + min(left, top-left, top)
19+
currRow[j] = 1 + minOf(currRow[j - 1], prevRow[j - 1], prevRow[j])
20+
}
21+
}
22+
maxLen = maxOf(maxLen, currRow[j])
23+
}
24+
// Update 'prevRow' with 'currRow' values for the next iteration.
25+
prevRow = currRow.copyOf()
26+
}
27+
return maxLen * maxLen
28+
}

0 commit comments

Comments
 (0)