LWC 63: 750. Number Of Corner Rectangles

LWC 63: 750. Number Of Corner Rectangles

传送门:750. Number Of Corner Rectangles

Problem:

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

A 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 grid1[2], grid1[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:

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

思路:
暴力搜索,实际上如果矩形的纵向边被确定了,只要有两条以上自然能构成矩形,所以只需要遍历不同的两行,找能够构成纵向边的个数,再组合一波即可。

Java版本:


    public int countCornerRectangles(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int ret = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                int np = 0;
                for (int k = 0; k < m; ++k) {
                    if (grid[i][k] == 1 && grid[j][k] == 1) {
                        np ++;
                    }
                }
                ret += np * (np - 1) / 2;
            }
        }
        return ret;
    }

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值