题意
给了一个字符串矩阵,求以次对角线方向对称的最大对称矩阵。
思路
每次只需求最外面一层对称个数sum,再和右上角对称矩阵大小加一取最小就行,就求出当前小矩阵的最大对称矩阵。最后取个所有对称矩阵大小的最大值就行。
dp[i][j] = min(sum,dp[i-1][j+1]+1);
开始没有将周围和右上取最小,遇到了周围是2×2(不是3×3),上面是2×2,但合起来并不能构成3×3的情况,看了题解才知道要两者取较小的那个
代码
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#define N 1005
#define INF 0x7f7f7f7f
using namespace std;
char val[ N ][ N ];
int dp[ N ][ N ];
int main () {
int n;
while ( ~scanf ( "%d", &n ) && n ) {
memset ( dp, 0, sizeof ( dp ) );
for ( int i = 0; i < n; ++i )
scanf ( "%s", val[ i ] );
int mx = 1;
for ( int x = 0; x < n; ++x ) {
for ( int y = 0; y < n; ++y ) {
//判断边界出了错
dp[ x ][ y ] = 1;
if ( x > 0 && y < n - 1 ) {
int t1 = x;
int t2 = y;
int sum = 0;
//找到两边对称的数量和上面的对称数+1取最小
while ( t1 >= 0 && t2 < n && val[ t1 ][ y ] == val[ x ][ t2 ] )
--t1, ++t2, ++sum;
dp[ x ][ y ] = min ( sum, dp[ x - 1 ][ y + 1 ] + 1 );
mx = max ( mx, dp[ x ][ y ] );
}
}
}
printf ( "%d\n", mx );
}
return 0;
}