Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12
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:
1 2 3 4 5 6 7 8 9 10 11
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.
// O(n^3) classSolution { public: intsumRange(vector<vector<int>>& matrix, int x0, int y0, int x1, int y1){ int ans = matrix[x1][y1]; if (y0 > 0) ans -= matrix[x1][y0-1]; if (x0 > 0) ans -= matrix[x0-1][y1]; if (x0>0 && y0>0) ans += matrix[x0-1][y0-1]; return ans; } intcountSquares(vector<vector<int>>& matrix){ int m = matrix.size(); int n = matrix[0].size(); for (int j = 1; j < n; ++j) { matrix[0][j] += matrix[0][j-1]; } for (int i = 1; i < m; ++i) { matrix[i][0] += matrix[i-1][0]; } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { matrix[i][j] += matrix[i-1][j] + matrix[i][j-1] - matrix[i-1][j-1]; } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int k = 1, x0 = i, y0 = j; x0 >= 0 && y0 >= 0; x0--, y0--, k++) { if (sumRange(matrix, x0, y0, i, j) == k*k) { ans++; } else { break; } } } } return ans; } };
代码2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// O(n^2) classSolution { public: intcountSquares(vector<vector<int>>& matrix){ int m = matrix.size(); int n = matrix[0].size(); int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] != 0 && i != 0 && j != 0) matrix[i][j] = 1+ min(matrix[i-1][j-1], min(matrix[i-1][j], matrix[i][j-1])); ans += matrix[i][j]; } } return ans; } };