Given a grid where each entry is only 0 or 1, find the number of corner rectangles.

corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need 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 2x3 and 3x2 rectangles, and one 3x3 rectangle.

Example 3:

Input: grid =
[[1, 1, 1, 1]]
Output: 0
Explanation: Rectangles must have four distinct corners. 

Note:

  1. The number of rows and columns of grid will each be in the range [1, 200].
  2. Each grid[i][j] will be either 0 or 1.
  3. The number of 1s in the grid will be at most 6000.

给了一个由0和1组成的二维数组,定义了一种边角矩形,其四个顶点均为1,求这个二维数组中有多少个不同的边角矩形。

不能一个一个的数,先固定2行,求每列与这2行相交是不是都是1 ,计算这样的列数,然后用公式:n*(n-1)/2,得出能组成的边角矩形,累加到结果中。

解法:枚举,枚举任意两行r1和r2,看这两行中存在多少列,满足在该列中第r1行和第r2行中对应的元素都是1。假设有counter列满足条件,那么这两行可以构成的的recangles的数量就是counter * (counter - 1) / 2。最后返回所有rectangles的数量即可。如果假设grid一共有m行n列,时间复杂度就是O(m^2n),空间复杂度是O(1)。如果m远大于n的时候,还可以将时间复杂度优化到O(mn^2)。

Java:

class Solution {
public int countCornerRectangles(int[][] grid) {
int m = grid.length, n = grid[0].length;
int ans = 0;
for (int x = 0; x < m; x++) {
for (int y = x + 1; y < m; y++) {
int cnt = 0;
for (int z = 0; z < n; z++) {
if (grid[x][z] == 1 && grid[y][z] == 1) {
cnt++;
}
}
ans += cnt * (cnt - 1) / 2;
}
}
return ans;
}
}  

Python:

def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
m = len(grid[0])
res = 0
for i in xrange(n):
for j in xrange(i + 1, n):
np = 0
for k in xrange(m):
if grid[i][k] and grid[j][k]:
np += 1 res += np * (np - 1) / 2
return res 

Python:

# Time:  O(n * m^2), n is the number of rows with 1s, m is the number of cols with 1s
# Space: O(n * m)
class Solution(object):
def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = [[c for c, val in enumerate(row) if val]
for row in grid]
result = 0
for i in xrange(len(rows)):
lookup = set(rows[i])
for j in xrange(i):
count = sum(1 for c in rows[j] if c in lookup)
result += count*(count-1)/2
return result

C++: 暴力,不好

class Solution {
public:
int countCornerRectangles(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), res = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
for (int h = 1; h < m - i; ++h) {
if (grid[i + h][j] == 0) continue;
for (int w = 1; w < n - j; ++w) {
if (grid[i][j + w] == 1 && grid[i + h][j + w] == 1) ++res;
}
}
}
}
return res;
}
};  

C++:

// Time:  O(m^2 * n), m is the number of rows with 1s, n is the number of cols with 1s
// Space: O(m * n)
class Solution {
public:
int countCornerRectangles(vector<vector<int>>& grid) {
vector<vector<int>> rows;
for (int i = 0; i < grid.size(); ++i) {
vector<int> row;
for (int j = 0; j < grid[i].size(); ++j) {
if (grid[i][j]) {
row.emplace_back(j);
}
}
if (!row.empty()) {
rows.emplace_back(move(row));
}
}
int result = 0;
for (int i = 0; i < rows.size(); ++i) {
unordered_set<int> lookup(rows[i].begin(), rows[i].end());
for (int j = 0; j < i; ++j) {
int count = 0;
for (const auto& c : rows[j]) {
count += lookup.count(c);
}
result += count * (count - 1) / 2;
}
}
return result;
}
};

C++:

class Solution {
public:
int countCornerRectangles(vector<vector<int>>& grid) {
int ans = 0;
for (int r1 = 0; r1 + 1 < grid.size(); ++r1) {
for (int r2 = r1 + 1; r2 < grid.size(); ++r2) {
int counter = 0;
for (int c = 0; c < grid[0].size(); ++c) {
if (grid[r1][c] == 1 && grid[r2][c] == 1) {
++counter;
}
}
ans += counter * (counter - 1) / 2;
}
}
return ans;
}
};

  

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 750. Number Of Corner Rectangles 边角矩形的数量的更多相关文章

  1. [LeetCode] Number Of Corner Rectangles 边角矩形的数量

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner rectang ...

  2. leetcode 750. Number Of Corner Rectangles

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner rectang ...

  3. 750. Number Of Corner Rectangles四周是点的矩形个数

    [抄题]: Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner r ...

  4. 【LeetCode】750. Number Of Corner Rectangles 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

  5. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  6. C#版 - Leetcode 191. Number of 1 Bits-题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  7. [leetcode]200. Number of Islands岛屿个数

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...

  8. [leetcode]694. Number of Distinct Islands你究竟有几个异小岛?

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...

  9. [LeetCode] 711. Number of Distinct Islands II_hard tag: DFS

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...

随机推荐

  1. Strength(HDU6563+2018年吉林站+双指针瞎搞)

    题目链接 传送门 题意 你有\(n\)只怪,每只怪的伤害为\(a_i\),对手有\(m\)只怪,每只怪的伤害为\(b_i\),对手的怪有普通状态和防守状态(普通状态:如果你用攻击力为\(a_i(a_i ...

  2. LOJ#2343. 「JOI 2016 Final」集邮比赛 2

    题目地址 https://loj.ac/problem/2343 题解 首先处理出\(f[i]\)表示以当前位置开头(J,O,I)的合法方案数.这个显然可以\(O(n)\)处理出来.然后考虑在每个位置 ...

  3. postgres高可用学习篇三:haproxy+keepalived实现postgres负载均衡

    环境: CentOS Linux release 7.6.1810 (Core) 内核版本:3.10.0-957.10.1.el7.x86_64 node1:192.168.216.130 node2 ...

  4. 2019牛客多校第九场AThe power of Fibonacci——扩展BM

    题意 求斐波那契数列m次方的前n项和,模数为 $1e9$. 分析 线性递推乘线性递推仍是线性递推,所以上BM. 由于模数非质数,上扩展版的BM. 递推多少项呢?本地输入发现最大为与前57项有关(而且好 ...

  5. 关于原生js的节点兼容性

    关于节点的兼容性: 1:获取元素的子节点 a: childNodes:获取元素的子节点,空文本,非空文本,注释,获取的比较全面, 如果只是想获取元素的子节点,请用(children) b:     c ...

  6. ESP8266 tcp透传AP+STA

    AP 建立WIFI,接受STA连接,串口数据和TCP互传 #include <ESP8266WiFi.h> const char *ssid = "esp8266_666&quo ...

  7. Guava com.google.common.base.Stopwatch Spark程序在yarn中 MethodNotFound

    今天在公司提交一个Spark 读取hive中的数据,写入JanusGraph 的app,自己本地调试没有问题,放入环境中提交到yarn 中时,发现app 跑不起. yarn 中日志,也比较明显,app ...

  8. 洛谷 P1379 八数码难题 题解

    我个人感觉就是一道bfs的变形,还是对bfs掌握不好的人有一定难度. 本题思路: 大体上用bfs搜,用map来去重,在这里只需要一个队列,因为需要较少步数达到的状态一定在步数较多的状态之前入队列. # ...

  9. 检验多个xsd的xml是否合法

    Java - 使用 XSD 校验 XML https://www.cnblogs.com/huey/p/4600817.html 这种方法不支持多个xsd文件,会报错 可以使用XMLBeans Too ...

  10. .net解决大文件断点续传

    以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载. 准备文件上传的API #region 文件上传  ...