[LeetCode] Number Of Corner Rectangles

750. Number Of Corner Rectangles

Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles.

A corner rectangle is four distinct 1’s on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1’s used must be distinct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int countCornerRectangles(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int res = 0;
for(int y1 = 0; y1 < n; y1++) {
for(int y2 = y1 + 1; y2 < n; y2++) {
int count = 0;
for(int x = 0; x < m; x++) {
if(grid[y1][x] and grid[y2][x]) count++;
}
res += count * (count - 1) / 2;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/02/PS/LeetCode/number-of-corner-rectangles/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.