- Number Of Corner Rectangles
中文English
Given a grid with only 0 and 1, find the number of corner rectangles.
Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.
Example
Example 1:
Input:
[
[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]
]
Output: 1
Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
Example 2:
Input:
[
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]
Output: 9
Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
Example 3:
Input: [[1,1,1,1]]
Output: 0
Explanation: Rectangles must have four distinct corners.
Notice
The number of rows and columns of grid will each be in the range [1, 200][1,200].
Each grid[i][j] will be either 0 or 1.
The number of 1s in the grid will be at most 6000.
解法1:
思路:先看第1行,然后第2到M行逐行跟第1行比,统计有1重合的数目。假设第i行跟第1行有1重合的数目为x,则新添矩形数目为C(x,2)=x*(x-1)/2,因为这x个1两两可以对应一个矩形。然后再看第2行,同样处理,直到一直处理完第M-1行。
代码如下。
class Solution {
public:
/**
* @param grid: the grid
* @return: the number of corner rectangles
*/
int countCornerRectangles(vector<vector<int>> &grid) {
int m = grid.size();
if (m == 0) return 0;
int n = grid[0].size();
int cnt = 0, sum = 0;
for (int i = 0; i < m - 1; i++) {
for (int j = i + 1; j < m; j++) {
int cnt = 0;
for (int k = 0; k < n; k++) {
if (grid[i][k] == 1 && grid[j][k] == 1) {
cnt++;
}
}
sum += cnt * (cnt - 1) / 2;
}
}
return sum;
}
};
本文介绍了一种算法,用于解决在一个仅包含0和1的网格中寻找角矩形的数量的问题。通过比较每行之间的1的位置来统计矩形数量,详细解释了实现过程和代码示例。
1752





