二维数组回形遍历 C++
关于输入
给定一个row行col列的整数数组array,要求从array[0][0]元素开始,按回形从外向内顺时针顺序遍历整个数组。如图所示:
输入的第一行上有两个整数,依次为row和col。
余下有row行,每行包含col个整数,构成一个二维整数数组。
(注:输入的row和col保证0<row<100, 0<col<100)
关于输出
按遍历顺序输出每个整数。每个整数占一行。
例子输入
4 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
例子输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
具体的思路就是:
设置开始遍历的行列、结束遍历的行列,
用四条边分别循环
循环边界条件是遍历数目为全部数目
有两个易错点:
1.最后一个数字需要单独处理
2.遍历到最后一行或列时,如果不及时退出循环,会有杂项
如[1,2,3,4,5],遍历完会再从右往左输出一遍。
//2020-11-1
#include <iostream>
using namespace std;
int main()
{
int row, col;
cin >> row >> col;
int a[101][101];
int count;
count = row * col;
for(int i = 0; i<row ;i++) //输入数据
for (int j = 0; j < col; j++)
{
cin >> a[i][j];
}
//回形读取
int it = 0, jt = 0;
int starti = 0, endi = row - 1, startj = 0, endj = col - 1;
while (count > 0)
{
while (jt < endj && count!=0) //上面行
{
cout << a[it][jt] << endl;
count--;
jt++;
}
starti++;
while (it < endi && count!=0) //右边列
{
cout << a[it][jt] << endl;
count--;
it++;
}
endj--;
while (jt > startj && count!=0) //下面行
{
cout << a[it][jt] << endl;
count--;
jt--;
}
endi--;
while (it > starti && count!=0) //左边列
{
cout << a[it][jt] << endl;
count--;
it--;
}
startj++;
if (count == 1) //最后一个数字手动处理
{
cout << a[it][jt] << endl;
count--;
}
}
return 0;
}