Description
Today is army day, but the servicemen are busy with the phalanx for the celebration of the 60th anniversary of the PRC.
A phalanx is a matrix of size n*n, each element is a character (a~z or A~Z), standing for the military branch of the servicemen on that position.
For some special requirement it has to find out the size of the max symmetrical sub-array. And with no doubt, the Central Military Committee gave this task to ALPCs.
A symmetrical matrix is such a matrix that it is symmetrical by the “left-down to right-up” line. The element on the corresponding place should be the same. For example, here is a 3*3 symmetrical matrix:
cbx
cpb
zcc
A phalanx is a matrix of size n*n, each element is a character (a~z or A~Z), standing for the military branch of the servicemen on that position.
For some special requirement it has to find out the size of the max symmetrical sub-array. And with no doubt, the Central Military Committee gave this task to ALPCs.
A symmetrical matrix is such a matrix that it is symmetrical by the “left-down to right-up” line. The element on the corresponding place should be the same. For example, here is a 3*3 symmetrical matrix:
cbx
cpb
zcc
Input
There are several test cases in the input file. Each case starts with an integer n (0<n<=1000), followed by n lines which has n character. There won’t be any blank spaces between characters or the end of line. The input file is ended with a 0.
Output
Each test case output one line, the size of the maximum symmetrical sub- matrix.
Sample Input
3
abx
cyb
zca
4
zaba
cbab
abbc
cacq
0
Sample Output
3
3
/* 题意:给你一个n*n的字符矩阵,让你求出,最大的对称矩阵的边长,对角线是从左下角到右上角 初步思路:递推 ,从右上角向下递推,dp[i][j]表示是以(i,j)为左下角的最大对称矩阵的边长,这样就得到状态转移方程: 从(i,j)开始向上,向右遍历,如果相等的长度>dp[i-1][j+1]的话,dp[i][j]=dp[i-1][j+1]+1,否则的话就是 dp[i-1][j+1]; #错误:还在找错误原因 */ #include <bits/stdc++.h> using namespace std; int n; char s[1005][1005]; int dp[1005][1005]; int maxn=0; void init(){ memset(dp,0,sizeof dp); maxn=1; } int main(){ // freopen("in.txt","r",stdin); while(scanf("%d",&n)!=EOF&&n){ init(); for(int i=1;i<=n;i++){ scanf("%s",s[i]+1); } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(i==1||j==n){ dp[i][j]=1; continue; } int a=i,b=j;//表示向上向右遍历的长度 while(a>=1&&b<=n&&s[a][j]==s[i][b]){ a--; b++; } // cout<<dp[i][j]<<" "; a=i-a; if(a>=dp[i-1][j+1]+1){ dp[i][j]=dp[i-1][j+1]+1; }else{ dp[i][j]=a; } maxn=max(dp[i][j],maxn); } // cout<<endl; } // for(int i=1;i<=n;i++){ // for(int j=1;j<=n;j++){ // cout<<dp[i][j]<<" "; // } // cout<<endl; // } printf("%d ",maxn); } return 0; }