蛇形填空是等考常考题型,通常是从某点出发,由内至外、或由外之内,或顺时针,或逆时针,依次填充。我们来看由外至内这个示例:
示例:
描述:在n*n方陈里填入1,2,..,n*n,要求填成蛇形。例如n=4时方阵为∶
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
输入:直接输入方阵的维数,即 n 的值。(n<=100)
输出:输出结果是蛇形方阵。
分析:
(1)方向设置
蛇形填空需要向下走、向左走、向上走和向右走四个方向。设某点坐标 (x,y),若:
向下走,其坐标为:(x+1,y)
向左走,其坐标为:(x,y-1)
向上走,其坐标为:(x-1,y)
向右走,其坐标为:(x,y+1)
(2)边界判断
方阵左上角的坐标为(0,0),右下角的坐标为(n-1,n-1),故此,
向下走:x+1 < n
向左走:y-1 >= 0
向上走:x-1 >= 0
向右走:y+1 < n
(3)标记填充状态
无论沿哪个方向进行填充,一个是要判断是否越界,另一个就是要判断是否填充过,如果填充过了,就不再填充了。方法就是初始化二维数组为0,0表示未填充,不是0表示已填充过。
C语言代码如下:
- #include
- #define N 100
- int main()
- {
- int x,y,n,a[N][N]={0},tot;
- scanf("%d",&n);
- x=0;
- y=n-1;
- a[x][y]=1;
- tot=1;
-
- while(tot
- {
- while(x+1
1][y]==0) //向下走 - {
- x++;
- tot++;
- a[x][y]=tot;
- }
-
- while(y-1>=0 && a[x][y-1]==0) //向左走
- {
- y--;
- tot++;
- a[x][y]=tot;
- }
-
- while(x-1>=0 && a[x-1][y]==0) //向上走
- {
- x--;
- tot++;
- a[x][y]=tot;
- }
-
- while(y+1
1]==0) //向右走 - {
- y++;
- tot++;
- a[x][y]=tot;
- }
- }
-
- for(x=0;x
- {
- for(y=0;y
- printf("%d ",a[x][y]);
- printf("\n");
- }
- return 0;
- }
python语言代码如下:
- n = int(input())
- # 初始化二维数组,这里用list实现,也可以用numpy下的array实现
- lst = []
- for i in range(n):
- l1 = [0] * n
- lst.append(l1)
-
- x = 0
- y = n - 1
- tot = lst[x][y] = 1
-
- while tot < n * n:
- while x+1 < n and lst[x+1][y] == 0: # 向下走
- x = x + 1
- tot = tot + 1
- lst[x][y] = tot
-
- while y-1 >= 0 and lst[x][y-1] == 0: # 向左走
- y = y - 1
- tot = tot + 1
- lst[x][y] = tot
-
- while x-1 >= 0 and lst[x-1][y] == 0: # 向上走
- x = x - 1
- tot = tot + 1
- lst[x][y] = tot
-
- while y+1 < n and lst[x][y+1] == 0: # 向右走
- y = y + 1
- tot = tot + 1
- lst[x][y] = tot
-
- for i in range(n):
- for j in range(n):
- print(lst[i][j], end=' ')
- print()
-
相关阅读:
纯虚函数和抽象类
HSV过滤灰色水印
大数据时代,怎样通过日志分析保护我们的数据!
内网渗透系列之mimikatz的使用以及后门植入
联邦学习中的安全多方计算
为什么要使用分布式锁
(附源码)ssm微课堂知识考核系统 毕业设计 141147
Qt篇——QTableWidget选中多行右键删除
GreenPlum DB向GBase迁移_TIME类型
编写递归函数,求斐波那契数列第n项
-
原文地址:https://blog.csdn.net/lvcheng0309/article/details/126502201