输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
int m,n,count;
//cin>>m>>n;
while(cin>>m>>n){ //多个测试样例,要用while循环,这里出错多次
int a[m][n];
count=m*n;
for (int i=0; i<m; i++)
{
for (int j=0; j<n; j++)
{
cin>>a[i][j];
}
}
int num=0,i=0,j=0;
while (num<count)
{
while (j<n&&a[i][j]!=-1)
{
cout<<a[i][j]<<" ";
a[i][j]=-1;
j++;
num++;
//cout<<"j"<<j;
//cout<<"A\n";
}
j--;
i++; //最终发现这里错了
//cout<<"j"<<j;
//cout<<"B\n";
while(i<m&&a[i][j]!=-1)//短路所以后面不会越界
{
cout<<a[i][j]<<" ";
a[i][j]=-1;
i++;
num++;
//cout<<"C\n";
}
i--;
j--;
//cout<<"j"<<j;
while (j>-1&&a[i][j]!=-1)
{
cout<<a[i][j]<<" ";
a[i][j]=-1;
j--;
num++;
}
j++;
i--;
while (i>-1&&a[i][j]!=-1)
{
cout<<a[i][j]<<" ";
a[i][j]=-1;
i--;
num++;
}
i++;
j++;
}
printf("\n");
}
return 0;
}
注意事项
1.循环开始结束的重要节点,边界条件
- 九度垃圾,多个测试样例要用while输入,单个一直报错还不告诉错在哪里,莫名其妙
网友评论