右螺旋阵
输入格式
一行,输入两个正整数n和m(2≤n,m≤30),分别表示行和列数
输出格式
输出对应的右螺旋矩阵
一个4*4的右螺旋矩阵是下面这个样子的:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
void generate(int n,int m,int mar[n][m])
{
int count=1;
int row_start=0,row_end=n-1;
int col_start=0,col_end=m-1;
while(row_start<=row_end&&col_start<=col_end)
{
for(int i=col_start;i<=col_end;i++)
{
mar[row_start][i]=count++;
}
row_start++;
for(int i=row_start;i<=row_end;i++)
{
mar[i][col_end]=count++;
}
col_end--;
if(row_start<=row_end)
{
for(int i=col_end;i>=col_start;i--)
{
mar[row_end][i]=count++;
}
row_end--;
}
if(col_start<=col_end)
{
for(int i=row_end;i>=row_start;i--)
{
mar[i][col_start]=count++;
}
col_start++;
}
}
}
左螺旋阵
一个4*4的左螺旋矩阵是下面这个样子的:
13 14 15 16
12 3 4 5
11 2 1 6
10 9 8 7
void generate(int n,int m,int mar[n][m])
{
int count=n*m;
int row_start=0,row_end=n-1;
int col_start=0,col_end=m-1;
int i=0;
while(row_start<=row_end&&col_start<=col_end)
{
for(i=col_end;i>=col_start;i--)
{
mar[row_start][i]=count--;
}
row_start++;
for(i=row_start;i<=row_end;i++)
{
mar[i][col_start]=count--;
}
col_start++;
if(row_start<=row_end)
{
for(i=col_start;i<=col_end;i++)
{
mar[row_end][i]=count--;
}
row_end--;
}
if(col_start<=col_end)
{
for(i=row_end;i>=row_start;i--)
{
mar[i][col_end]=count--;
}
col_end--;
}
}
}
完整代码(左螺旋阵)
#include <stdio.h>
void generate(int n,int m,int mar[n][m])
{
int count=n*m;
int row_start=0,row_end=n-1;
int col_start=0,col_end=m-1;
int i=0;
while(row_start<=row_end&&col_start<=col_end)
{
for(i=col_end;i>=col_start;i--)
{
mar[row_start][i]=count--;
}
row_start++;
for(i=row_start;i<=row_end;i++)
{
mar[i][col_start]=count--;
}
col_start++;
if(row_start<=row_end)
{
for(i=col_start;i<=col_end;i++)
{
mar[row_end][i]=count--;
}
row_end--;
}
if(col_start<=col_end)
{
for(i=row_end;i>=row_start;i--)
{
mar[i][col_end]=count--;
}
col_end--;
}
}
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int mar[n][m];
generate(n,m,mar);
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d ",mar[i][j]);
}
printf("\n");
}
return 0;
}