Blue Bridge Cup test questions basic exercises round access matrix return traversal output

Title link: http://lx.lanqiao.cn/problem.page?gpid=T66

Blue Bridge Cup basic exercises

Resource limit
Time limit: 1.0s Memory limit: 512.0MB
Problem description The
  number of rounds is taken along the edge of the matrix. If there are countless available or already taken in the current direction, turn left 90 degrees. It is initially located in the upper left corner of the matrix, with the direction down.
Input format The
  first row of input is two positive integers m, n not exceeding 200, which represent the rows and columns of the matrix. The next m rows and n integers per row represent this matrix.
Output format The
  output is only one line, with a total of mn numbers. It is the result obtained by taking the input matrix round shape. The numbers are separated by a space, and there should be no extra spaces at the end of the line.
Sample input
3 3
1 2 3
4 5 6
7 8 9
Sample output
1 4 7 8 9 6 3 2 5
Sample input
3 2
1 2
3 4
5 6
Sample output
1 3 5 6 4 2

Solution: There is always a certain order when traversing the output: down, right, up, left. . . Form a loop, pay attention to control the output format, and determine whether you need to rotate 90 degrees. Until all data output stops. Directly enter the AC code:

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int s[10009];
int main(int argc, char** argv) {
	int a[210][210];
	int m,n;
	cin>>m>>n;
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			scanf("%d",&a[i][j]);
		}
	}
	int i=-1,j=0,k=0;
     while(k<m*n)
     {
     	while(a[++i][j]!=-1&&i<m)                //向下 
     	{
     	     if(k==0)
			  {
			  	cout<<a[i][j];
			  }
			  else cout<<' '<<a[i][j];  	
			  k++;
			  a[i][j]=-1;
		}
		i--;
		while(a[i][++j]!=-1&&j<n)        //向右 
		{
			if(k==0) cout<<a[i][j];
			else cout<<' '<<a[i][j];
			k++;
			a[i][j]=-1;
		 } 
		 j--;
		 while(a[--i][j]!=-1&&i>=0)          //向上 
		 {
		 	 cout<<' '<<a[i][j];
		 	 k++;
		 	 a[i][j]=-1;
		 }
		 i++;
		 while(a[i][--j]!=-1&&j>=0)      //向左 
		 {
		 	cout<<' '<<a[i][j];
		 	k++;
		 	a[i][j]=-1;
		 }
		 j++;
	 }
	 cout<<'\n';
	return 0;
}
Published 6 original articles · Like1 · Visits 141

Guess you like

Origin blog.csdn.net/qq_46015269/article/details/105491358