返回题解分享
讨论 / 题解分享/ 帖子详情

蛇形填数2 - 题解

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'

int main()
{
int m,n;
scanf("%d %d",&m,&n);
int dir=1;
vector<vector<int>> arr(m,vector<int>(n));
// int arr[100][100];
int x,y,bound_x,bound_y;
bound_x=m;
bound_y=n;
x = 0;
y = n-1;
int cir = 0;
for(int cnt=1;cnt<=m*n;cnt++)
{

if(dir==1)
	{
		arr[x][y] = cnt;
		x++;
		if(x == (bound_x-cir))
		{
			dir = 2;
			x--;
			y--;
		}
	}
	else if(dir==2)
	{
		arr[x][y] = cnt;
		y--;
		if(y == (cir-1))
		{
			dir = 3;
			y++;
			x--;
		}
	}
	else if(dir==3)
	{
		arr[x][y] = cnt;
		x--;
		if(x == (cir -1))
		{
			dir =4;
			x++;
			y++;
		}
	}
	else if(dir ==4 )
	{
		arr[x][y] = cnt;
		y++;
		if(y == (n-cir-1)) 
		{
			dir = 1;
			y--;x++;
			cir++;
		}
	}
}
for(int i = 0; i < m;i++)
{
	for(int j = 0;j < n;j++)
	{
		printf("%5d",arr[i][j]);
	}
	cout<<endl;
}

return 0;


}
0 回复 0 转发 0 喜欢 2 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!