1277. Statistics are all square sub-matrix 1

1. Topic

You give a m * n matrix, the matrix element of either 0 or 1, and return to where you count the number of square sub-matrix 1 is entirely composed.

Example 1:

Input: Matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
a square of 1 with 10.
A square of 2 has four.
A square of 3 have a.
Number of squares = 10 + 4 + 1 = 15.
Example 2:

Input: Matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
a square of one of the six.
A square of a 2 there.
Number of squares = 6 + 1 = 7.

prompt:

1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1

2. problem solution

The official solution to a problem using a proven formula, left God said, really do question when the time is impossible to do mathematical proofs, only the feel and experience. I had thought of comparing each point to its left, top, and the relationship between the upper left three points, but I did not find a relationship to give up.

Can create a new and original as the size of the matrix elements of each point represents to the lower right corner of the node when the number of squares can make up the most . The relationship is mathematical induction:
a [ x ] [ y ] = m i n ( a [ x 1 ] [ y ] , a [ x ] [ y 1 ] , a [ x 1 ] [ y 1 ] ) to [x] [y] = min ([x-1] [y] to [x] [y-1], a [x-1] [y-1])
  in the title actually do when probably guess just fine, but in my opinion this question can be considered a type of problem.

3. Source

leetcode has been demonstrated

#include "pch.h"
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_set>
#include <string>
#include <vector>

using namespace std;
int cc(vector<vector<int>>&mm, vector<vector<int>> &a,int x, int y)
{
	int count = INT_MAX;
	if (1 != mm[x][y])
		return 0;

	if (x - 1 >= 0)
		count = min(count, a[x - 1][y]);
	else
		count = 0;

	if (y - 1 >= 0)
		count = min(count, a[x][y - 1]);
	else
		count = 0;
	if (x - 1 >= 0 && y - 1 >= 0)
		count = min(count, a[x - 1][y - 1]);
	else
		count = 0;

	a[x][y] = count + 1;
	return a[x][y];
}
int countSquares(vector<vector<int>>& matrix) {
	if (matrix.empty())
		return 0;
	int x = matrix.size();
	int count = 0;
	if (x <= 0)
		return 0;
	int y = matrix[0].size();

	vector<vector<int>>a(x, vector<int>(y));

	for (int i = 0; i < x; ++i) ///<行
		for (int j = 0; j < y; ++j)
			count += cc(matrix, a,i, j);

	return count;
}
int main()
{
	vector<vector<int>>matrix;
	int qq[]= {0,1,1,1};
	int qq1[] = {1,1,1,1};
	int qq2[] = {0,1,1,1};

	vector<int>temp(begin(qq),end(qq));
	vector<int>temp1(begin(qq1),end(qq1));
	vector<int>temp2(begin(qq2),end(qq2));
	matrix.push_back(temp);
	matrix.push_back(temp1);
	matrix.push_back(temp2);
	cout << countSquares(matrix) << endl;
	system("pause");
	return 0;
}

Published 21 original articles · won praise 1 · views 10000 +

Guess you like

Origin blog.csdn.net/qigezuishuaide/article/details/103652143