• 蛇形填空 I


    蛇形填空是等考常考题型,通常是从某点出发,由内至外、或由外之内,或顺时针,或逆时针,依次填充。我们来看由外至内这个示例:

    示例:

    描述:在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语言代码如下:

    1. #include
    2. #define N 100
    3. int main()
    4. {
    5. int x,y,n,a[N][N]={0},tot;
    6. scanf("%d",&n);
    7. x=0;
    8. y=n-1;
    9. a[x][y]=1;
    10. tot=1;
    11. while(tot
    12. {
    13. while(x+11][y]==0) //向下走
    14. {
    15. x++;
    16. tot++;
    17. a[x][y]=tot;
    18. }
    19. while(y-1>=0 && a[x][y-1]==0) //向左走
    20. {
    21. y--;
    22. tot++;
    23. a[x][y]=tot;
    24. }
    25. while(x-1>=0 && a[x-1][y]==0) //向上走
    26. {
    27. x--;
    28. tot++;
    29. a[x][y]=tot;
    30. }
    31. while(y+11]==0) //向右走
    32. {
    33. y++;
    34. tot++;
    35. a[x][y]=tot;
    36. }
    37. }
    38. for(x=0;x
    39. {
    40. for(y=0;y
    41. printf("%d ",a[x][y]);
    42. printf("\n");
    43. }
    44. return 0;
    45. }

    python语言代码如下:

    1. n = int(input())
    2. # 初始化二维数组,这里用list实现,也可以用numpy下的array实现
    3. lst = []
    4. for i in range(n):
    5. l1 = [0] * n
    6. lst.append(l1)
    7. x = 0
    8. y = n - 1
    9. tot = lst[x][y] = 1
    10. while tot < n * n:
    11. while x+1 < n and lst[x+1][y] == 0: # 向下走
    12. x = x + 1
    13. tot = tot + 1
    14. lst[x][y] = tot
    15. while y-1 >= 0 and lst[x][y-1] == 0: # 向左走
    16. y = y - 1
    17. tot = tot + 1
    18. lst[x][y] = tot
    19. while x-1 >= 0 and lst[x-1][y] == 0: # 向上走
    20. x = x - 1
    21. tot = tot + 1
    22. lst[x][y] = tot
    23. while y+1 < n and lst[x][y+1] == 0: # 向右走
    24. y = y + 1
    25. tot = tot + 1
    26. lst[x][y] = tot
    27. for i in range(n):
    28. for j in range(n):
    29. print(lst[i][j], end=' ')
    30. print()

  • 相关阅读:
    纯虚函数和抽象类
    HSV过滤灰色水印
    大数据时代,怎样通过日志分析保护我们的数据!
    内网渗透系列之mimikatz的使用以及后门植入
    联邦学习中的安全多方计算
    为什么要使用分布式锁
    (附源码)ssm微课堂知识考核系统 毕业设计 141147
    Qt篇——QTableWidget选中多行右键删除
    GreenPlum DB向GBase迁移_TIME类型
    编写递归函数,求斐波那契数列第n项
  • 原文地址:https://blog.csdn.net/lvcheng0309/article/details/126502201