详情点击这里
题目:
给定两个整数M,N,生成一个M*N的矩阵,矩阵中元素取值为A至Z的26个字母中的一个,A在左上角,其余各数按顺时针方向旋转前进,依次递增放置,当超过26时又从A开始填充。例如,当M=5,N=8时,矩阵中的内容如下:
A B C D E F G H
V W X Y Z A B I
U J K L M N C J
T I H G F E D K
S R Q P O N M L
Input
M为行数,N为列数,其中M,N都为大于0的整数。
Output
分行输出相应的结果
Sample Input
4 9
Sample Output
A B C D E F G H I
V W X Y Z A B C J
U J I H G F E D K
T S R Q P O N M L
AC的C++代码如下(递归):
#include
#include
using namespace std;
const int N = 101;
char a[N][N];
int n, m, k;
char b[26] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
void dfs(int n, int m, int p)
{
if (n <= 0 || m <= 0)
return;
if (n == 1)
{
for (int i = p; i < m + p; i++)
{
a[p][i] = b[k++];
if (k == 26)
k = 0;
}
return;
}
if (m == 1)
{
for (int i = p; i < n + p; i++)
{
a[i][p] = b[k++];
if (k == 26)
k = 0;
}
return;
}
for (int i = p; i < m + p - 1; i++)
{
a[p][i] = b[k++];
if (k == 26)
k = 0;
}
for (int i = p; i <= n + p - 1; i++)
{
a[i][m + p - 1] = b[k++];
if (k == 26)
k = 0;
}
k--;
for (int i = m + p - 1; i >= p; i--)
{
a[n + p - 1][i] = b[k++];
if (k == 26)
k = 0;
}
for (int i = n + p - 1; i > p + 1; i--)
{
a[i - p + p - 1][p] = b[k++];
if (k == 26)
k = 0;
}
dfs(n - 2, m - 2, p + 1 );
}
int main()
{
cin >> n >> m;
dfs(n, m, 1);
for (int i = 1; i <= n; i++)
{
for (int r = 1; r <= m; r++)
cout << " " << a[i][r];
cout << endl;
}
cout << endl;
}
AC的C++代码如下
#include
#include
#include
using namespace std;
int n,m;
int a[1000][1000];
void ss(int l,int x,int y,int ans)
{
//printf("%d %d\n",x,y);
if(a[x][y]!=0)
return;
if(l==0)
{
//printf("%d\n",ans);
a[x][y]=ans;
ans++;
if(a[x][y+1]==0&&y+1<m)
{
ss(l,x,y+1,ans);
}
else
ss(l+1,x+1,y,ans);
}
else if(l==1)//向下
{
a[x][y]=ans;
ans++;
if(a[x+1][y]==0&&x+1<n)
{
ss(l,x+1,y,ans++);
}
else
ss(l+1,x,y-1,ans++);
}
else if(l==2)//向左
{
a[x][y]=ans;
ans++;
if(a[x][y-1]==0&&y-1>=0)
{
ss(l,x,y-1,ans++);
}
else
ss(l+1,x-1,y,ans++);
}
else if(l==3)//向上
{
a[x][y]=ans;
ans++;
if(a[x-1][y]==0&&x-1>=0)
{
ss(l,x-1,y,ans++);
}
else
ss(0,x,y+1,ans++);
}
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
int i=0,j=0,s=0,k=0,l;
memset(a,0,sizeof(a));
ss(0,0,0,1);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf(" %c",(a[i][j]-1)%26+'A');//输出
}
printf("\n");
}
}
return 0;
}