问题:
难度:easy
说明:
给定一个二维数组,里面数据只有0 1将里面所有的1组成的正方形统计出来。
输入案例:
Example 1:
// 边长1的正方形有10个,边长2的正方形有4个,边长3正方形有1个,所以一共15个,下同
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
我的代码:
具体想法跟动态规划差不多,但是我是把每行联通块大小统计,然后统计 边长 <= 一行联通块大小 的正方形有多少个,在leetcode跑是5ms和9ms浮动。
class Solution {
public int countSquares(int[][] matrix) {
int count = 0;
int xlen =