前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 63: 750. Number Of Corner Rectangles

LWC 63: 750. Number Of Corner Rectangles

作者头像
用户1147447
发布2018-01-02 10:01:24
7050
发布2018-01-02 10:01:24
举报
文章被收录于专栏:机器学习入门机器学习入门

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版本:

代码语言:javascript
复制
    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版本:

代码语言:javascript
复制
    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  
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 63: 750. Number Of Corner Rectangles
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档