代码:
#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main() {
int m,n;
int left=0,top=0;
cin>>n>>m;
int right=m-1,bottom=n-1;
int k=1;
while(left<=right||top<=bottom) {
for(int i=left; i<=right&&top<=bottom; i++) {
a[top][i]=k++;
}
top++;
for(int i=top; i<=bottom&&left<=right; i++) {
a[i][right]=k++;
}
right--;
for(int i=right; i>=left&&top<=bottom; i--) {
a[bottom][i]=k++;
}
bottom--;
for(int i=bottom; i>=top&&left<=right; i--) {
a[i][left]=k++;
}
left++;
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
cout<<a[i][j];
if(j!=m-1)
cout<<" ";
}
if(i!=n-1)
cout<<endl;
}
return 0;
}
分析:
从题目描述中可以分析出,蛇形矩阵就是从矩阵的左上角->右上角->右下角->左下角的一个由外向内的循环。那么我们就可以通过模拟这样的过程给数组赋值,从而得到我们想要的结果并输出。
代码段落分析:
while(left<=right||top<=bottom) {
for(int i=left; i<=right&&top<=bottom; i++) {
a[top][i]=k++;
}
top++;
for(int i=top; i<=bottom&&left<=right; i++) {
a[i][right]=k++;
}
right--;
for(int i=right; i>=left&&top<=bottom; i--) {
a[bottom][i]=k++;
}
bottom--;
for(int i=bottom; i>=top&&left<=right; i--) {
a[i][left]=k++;
}
left++;
}
第一个for循环,i控制列从left->right,并且行top始终不变,可以将数组从第top行的第left个遍历到第right个。而循环条件可以保证在整个while循环中,这一个for循环始终控制的是矩阵最上端的一行。
第二个for循环,i控制行从top->bottom,并且列right始终不变,可以将数组从第right列的第top个遍历到第bottom个。循环条件可以保证在整个while循环中,这一个for循环始终控制的是矩阵最右端的一列。
同理,第三个循环控制最下端的一行,第四个循环控制最左端的一列。