欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二维数组回形遍历 C++

程序员文章站 2022-04-05 11:49:59
...

二维数组回形遍历 C++

二维数组回形遍历 C++
二维数组回形遍历 C++
二维数组回形遍历 C++

具体的思路就是:
设置开始遍历的行列、结束遍历的行列,
用四条边分别循环
循环边界条件是遍历数目为全部数目

有两个易错点:
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;
}
相关标签: c++