洛谷刷题4:蛇形方阵(洛谷P5731)
题目描述
给出一个不大于 9 的正整数 n,输出 n×n 的蛇形方阵。
从左上角填上 1 开始,顺时针方向依次填入数字,如同样例所示。注意每个数字有都会占用 3 个字符,前面使用空格补齐。
输入输出样例
输入 #1
4
输出 #1
题目也不难,但是题解中有走地图的思路,在这里记录一下:1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<math.h>
using namespace std;
int a[100];
int map[200][200];
int pos[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };//四个变化分别是:向右,向下,向左,向上
int main()
{
int n;
cin >> n;
for (int x = 1, y = 1, p = 0, i = 1; i <= n*n;i++)
{
map[x][y] = i;
int next_x = x + pos[p][0], next_y = y + pos[p][1];
if ((next_x<1 || next_x>n || next_y<1 || next_y>n) || map[next_x][next_y])p = (p + 1) % 4;
//就像贪吃蛇一样,如果碰到边界了或者碰到数了,就掉头,而且是以右下左上的顺序掉头,形成蛇形
x += pos[p][0], y += pos[p][1];
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << setw(3) << map[i][j];
}
cout << endl;
}
return 0;
}
重点是数组pos[4][2]的运用,实现位置的变动,使得掉头什么的变得容易

浙公网安备 33010602011771号