Question:
For a square matrix composed of 1 and 0, calculate the number of squares where all four edges are composed of 1.
Method:
First, count each point in the matrix in four directions, and the maximum number of consecutive 1 values. Here we use DP to do the same.
At the same time, by the way, the side length of the largest square that can be formed in the right bottom and top left sides (that is, the D1 [] [] D2 [] [])
Why in these two directions? This makes it easy to calculate the longest continuous 1. It seems that the four directions cannot work together.
Then the enumerated edge length is gone.
Wrong question during the competition, I thought it was solid.
I think this question very much. I don't even know what category I got.
These solutions are clear and concise.
# Include <iostream> # include <cmath> # include <cstdio> # include <vector> # include <cstring> # include <algorithm> using namespace STD; int T, T, ANS, s [1005] [1005], n; int D1 [1005] [1005], D2 [1005] [1005], DT [1005] [1005], dd [1005] [1005], DL [1005] [1005], Dr [1005] [1005]; // DT (top) dd (down) DL (left) dr (right) indicates the maximum length of the vertex to four directions. 1 // D1 indicates the maximum length of the diagonal line to the right of the vertex (that is, the shorter side to the right of the vertex) d2 indicates to the upper left int main () {int I, j, k; scanf ("% d", & T); t = 0; while (t --) {ans = 0; t ++; scanf ("% d", & N); for (I = 0; I <n; I ++) for (j = 0; j <n; j ++) {scanf ("% d", & S [I] [J]); If (s [I] [J]) ans ++;} memset (DT, 0, sizeof DT); memset (DD, 0, sizeof dd); memset (DR, 0, sizeof Dr); memset (DL, 0, sizeof dl); for (I = 0; I <n; I ++) // right bottom direction {for (j = 0; j <n; j ++) {If (s [I] [J]) {dd [I] [J] = dd [I-1] [J] + 1; dr [I] [J] = Dr [I] [J-1] + 1;} D1 [I] [J] = min (Dd [I] [J], dr [I] [J]) ;}}for (I = n-1; I> = 0; I --) // {for (j = n-1; j> = 0; j --) {If (s [I] [J]) {dt [I] [J] = dt [I + 1] [J] + 1; DL [I] [J] = DL [I] [J + 1] + 1;} D2 [I] [J] = min (dt [I] [J], DL [I] [J]) ;}}for (I = 0; I <n; I ++) {for (j = 0; j <n; j ++) {for (k = 2; k <= d2 [I] [J]; k ++) // enumerative side length {If (k <= D1 [I + k-1] [J + k-1]) ans ++ ;}} printf ("case % d: % d \ n ", T, ANS);} return 0 ;}