1.8 23:二维数组回形遍历

描述
给定一个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

#include <iostream>
using namespace std;
#define MAX 101
int main()
{
	int col,row,a[MAX][MAX],count,k,i,j;
	cin>>row>>col;
	for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			scanf("%d", &a[i][j]);
		}		
	}
	if(row==1)
	{
		i=0;
		j=0;
		for(j;j<col;j++)
		{
			cout<<a[i][j]<<endl;
		}
	}else if(col==1)
	{
		i=0;
		j=0;
		for(i;i<row;i++)
		{
			cout<<a[i][j]<<endl;
		}
	}else
	{
		i=0;
		j=0;
		count = col*row;
		while(count>0)
		{
			
			for(k=1;k<col;k++)
			{
				cout<<a[i][j++]<<endl;
				count--;
			}
			for(k=1;k<row;k++)
			{
				cout<<a[i++][j]<<endl;
				count--;
			}
			for(k=1;k<col;k++)
			{
				cout<<a[i][j--]<<endl;
				count--;
			}
			for(k=1;k<row;k++)
			{
				cout<<a[i--][j]<<endl;
				count--;
			}
			row -= 2;
			col -= 2;
			i++;
			j++;
			if(row==1)
			{
				for(k=1;k<=col;k++)
				{
					cout<<a[i][j++]<<endl;
					count--;
				}
			} else if(col==1)
			{
				for(k=1;k<=row;k++)
				{
					cout<<a[i++][j]<<endl;
					count--;
				}
			}
		}
	}
	
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值