题目:蛇形矩阵
题目的大意是这样:
输入2
矩阵为:
1 2
4 3
输出:1 2 4 3 //按行打印
输入:3
矩阵为:
1 2 3
8 9 4
7 6 5
输出: 1 2 3 8 9 4 7 6 5
下面给出具体的代码:
#include<iostream>
#include<vector>
using namespace std;
void fun(const int n)
{
vector<int> elem;
elem.resize(n);
vector<vector<int> >array(n,elem);
int count = 0;
int topleft[2] = {0,0};
int topright[2] = {0,n - 1};
int bottomleft[2] = {n - 1,0};
int bottomright[2] = {n - 1,n - 1};
int col = 0,row = 0;
int i = 0, j = 0;
while(true){
row = topleft[0];
col = topleft[1];
while(col <= topright[1]){
array[row][col++] = ++count;
}
topright[1] -= 1;
topright[0] += 1;
row = topright[0];
col = topright[1] + 1;
while(row <= bottomright[0]){
array[row++][col] = ++count;
}
bottomright[0] -= 1;
bottomright[1] -= 1;
col = bottomright[1];
row = bottomright[0] + 1;
while(col >= bottomleft[1]){
array[row][col--] = ++count;
}
bottomleft[0] -= 1;
bottomleft[1] += 1;
row = bottomleft[0];
col = bottomleft[1] - 1;
while(row > topleft[0]){
array[row--][col] = ++count;
}
topleft[0] += 1;
topleft[1] += 1;
if(topleft[1] >= topright[1]){
if(n % 2 != 0){
array[n / 2][n / 2] = ++count;
}
break;
}
}
for(i = 0;i < n; i++){
for(j = 0;j < n;j++){
cout << array[i][j] <<" ";
}
cout << endl;
}
}
int main(int argc,char**argv)
{
int n = 0;
cin>>n;
fun(n);
return 0;
}
程序的执行结果:
该程序需要判断n的奇偶,当n为奇数时,在矩阵的最中间还要放一个数,当n为偶数时,则不用放。
下面给出一种比较简便的方法:
void fun1(const int n)
{
int i,j,k;
int array[n][n];
int cnt = 0;
for(k = 0; k < n / 2;k++){
i = k;
for(j = k;j < n - 1 - k;j++){
array[i][j] = ++cnt;
}
for(;i < n - 1 - k;i++){
array[i][j] = ++cnt;
}
for(;j > k;j--){
array[i][j] = ++cnt;
}
for(;i > k;i--){
array[i][j] = ++cnt;
}
}
if(n % 2){
array[n / 2][n / 2] = ++cnt;
}
for(i = 0;i < n; i++){
for(j = 0;j < n;j++){
cout << array[i][j] <<" ";
}
cout << endl;
}
}
其执行结果是和上面的一模一样的。。。
该思路就是一圈一圈的进行打印,所以大的循环要进行n/2次,因为有n/2个大圈,每个大圈又分为向右打印,向下打印,向左打印,向上打印,打印时要注意:把角上的元素放在下一次打印的首个元素,这样可以起到过渡的作用。。。
第一种方法应该是官方给出的答案,个人认为第二种方法比较好。。。。