//#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
/*在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
*/
int main() {
int n;
cin >> n;//输入方阵边长
int a[100][100] = { 0 };//所有元素初始化为0,便于判断
int i, x = 0, y = n - 1;//x:行,y:列
a[0][n - 1] = 1;//赋第一个数
int num = 1;//累++
while (num < n * n) {//最大数为n*n
//使下一次赋值的位置(x+1)不出阵,且该位置未赋过值
while (x + 1 < n && a[x + 1][y] == 0)//向下
a[++x][y] = ++num;
while (y - 1 >= 0 && a[x][y - 1] == 0)//向左
a[x][--y] = ++num;
while (x - 1 >= 0 && a[x - 1][y] == 0)//向上
a[--x][y] = ++num;
while (y + 1 < n && a[x][y + 1] == 0)//向右
a[x][++y] = ++num;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
//system("pause");
return 0;
}
ACM 蛇形填数c++语言实现
最新推荐文章于 2024-05-26 11:37:30 发布