Given a grid where each entry is only 0 or 1, find thenumber of corner rectangles.
A corner rectangle is 4 distinct 1son the grid that form an axis-aligned rectangle. Note that only the cornersneed to have the value 1. Also, all four 1s used must be distinct.
Example 1:
Input: grid =
[[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: grid =
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Output: 9
Explanation: There are four 2x2 rectangles, four 2x3and 3x2 rectangles, and one 3x3 rectangle.
Example 3:
Input: grid =
[[1, 1, 1, 1]]
Output: 0
Explanation: Rectangles must have four distinctcorners.
Note:
1. The number of rows and columns of grid willeach be in the range [1, 200].
2. Each grid[i][j] will be either 0 or 1.
3. The number of 1s inthe grid will be at most 6000
给定一个矩阵,求矩阵里面有多少个1围成的矩形,看起来很简单,但是要不超时却很困难,这题假如用暴力解决的话一定会超时的,所以需要使用不一样的方法,
以后在编程的时候记住#define FILL(x,y) memset(x,y,sizeof(x))这样写能节省很多的时间
class Solution {
public:
#defineREP(i,s,t) for(int i=s;i<=t;i++)
#defineFILL(x,y) memset(x,y,sizeof(x))
#define MAX 205
int cell[MAX][MAX];
intcountCornerRectangles(vector<vector<int>>& grid) {
FILL(cell, 0);
int w, h;
w = grid[0].size();
h = grid.size();
int count = 0;
REP(x, 0, h - 1)
{
REP(i, 0, w - 2)
REP(j, i+1, w - 1)
if (grid[x][i] == 1 &&grid[x][j] == 1) { count += cell[i][j]; cell[i][j] += 1; }
}
return count;
}
};
8669




被折叠的 条评论
为什么被折叠?



