Skip to content

Commit b314a08

Browse files
committed
1277. Count Square Submatrices with All Ones
1 parent e0542d3 commit b314a08

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -764,6 +764,7 @@ BFS, DFS, Dijkstra, Floyd–Warshall, Bellman-Ford, Kruskal, Prim's, Minimum Spa
764764
|56| **[689. Maximum Sum of 3 Non-Overlapping Subarrays](https://tinyurl.com/y9nlm8tg)** | [Python](https://tinyurl.com/wu6rdaw/689_Maximum_Sum_of_3_Non_Overlapping_Subarrays.py), [Swift](https://tinyurl.com/wuja3c4/689_Maximum_Sum_of_3_Non_Overlapping_Subarrays.swift)| **[Art 1](https://tinyurl.com/__)** | Hard | **Mainly, tricly array index manipulation. TODO: need to solve it in DP and sliding window approach** |
765765
|57| **[338. Counting Bits](https://tinyurl.com/y5ly38nj)** | [Python](https://tinyurl.com/wu6rdaw/338_Counting_Bits.py), [Swift](https://tinyurl.com/wuja3c4/338_Counting_Bits.swift)| | Medium | --- |
766766
|58| **[1269. Number of Ways to Stay in the Same Place After Some Steps](https://tinyurl.com/y43jo8j3)** | [Python](https://tinyurl.com/wu6rdaw/1269_Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.py), [Swift](https://tinyurl.com/wuja3c4/1269_Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.swift)| [Art 1](https://tinyurl.com/yynv9xe2) | Hard | Loved the problem. Very versatile |
767+
|59| **[1277. Count Square Submatrices with All Ones](https://tinyurl.com/y6a82a9r)** | [Python](https://tinyurl.com/wu6rdaw/1277_Count_Square_Submatrices_with_All_Ones.py), [Swift](https://tinyurl.com/wuja3c4/1277_Count_Square_Submatrices_with_All_Ones.swift)| [Must](https://tinyurl.com/y4sa8zgk) | Medium | --- |
767768

768769

769770
</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import Foundation
2+
class Solution {
3+
func countSquares(_ matrix: [[Int]]) -> Int {
4+
let (rows, cols) = (matrix.count, matrix[0].count)
5+
guard rows > 0, cols > 0 else {
6+
return 0
7+
}
8+
var dp = matrix
9+
var result = 0
10+
for i in 0..<rows {
11+
for j in 0..<cols {
12+
if matrix[i][j] == 1 {
13+
if i == 0 || j == 0 {
14+
result += 1
15+
} else {
16+
var cellValue = 1
17+
if let minNeighbour = [ dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j] ].min() {
18+
cellValue += minNeighbour
19+
}
20+
result += cellValue
21+
dp[i][j] = cellValue
22+
}
23+
}
24+
}
25+
}
26+
return result
27+
}
28+
}

0 commit comments

Comments
 (0)