首页 > 试题广场 >

蛇形矩阵

[编程题]蛇形矩阵
  • 热度指数:6316 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给你一个整数n,输出n∗n的蛇形矩阵。

输入描述:
输入一行,包含一个整数n


输出描述:
输出n行,每行包含n个正整数,通过空格分隔。

1<=n<=1000
示例1

输入

4

输出

1 2 6 7
3 5 8 13
4 9 12 14
10 11 15 16
n =  int(input())  # map函数用法
arr = [ ['']*n  for _ in range(n)]
i = 0  #  行索引
j = 0  #  列索引
count = 1  # 元素值

arr[i][j] = count # 按蛇形路线确定循环一个周期的的开始

while True:
    # 矩阵最上方只能 右移或下移
    if j+1 < n: # 右移
        j += 1
        count += 1
        arr[i][j] = count
    else :
        if i+1 < n:  # 下移
            i += 1
            count += 1
            arr[i][j] = count
    
    while True:
        if  i+1 < n and 0 <= j-1 : # 左下
            i += 1
            j -= 1
            count += 1
            arr[i][j] = count

        elif  i+1 < n  :  # 全部左下后,能下移一格,则执行
            i += 1
            count += 1
            arr[i][j] = count
            #下移一格后,右上,全部右上后,抵达周期的开始,break结束最近的 while
            for _ in range(i): 
                if 0 <= i-1   and j+1 < n:  # 右上
                    i -= 1
                    j += 1
                    count += 1
                    arr[i][j] = count
            break
            
        elif  j+1 < n:  # 全部左下后,不能下移一格,则判断能否向右一格
            j += 1
            count += 1
            arr[i][j] = count
            #  右上,全部右上后,抵达周期的开始,break结束最近的 while
            for _ in range(i): 
                if 0 <= i-1   and  j+1 < n:  # 右上
                    i -= 1
                    j += 1
                    count += 1
                    arr[i][j] = count
            break
    if i==j and i+1==n:
        break 
for i in arr:
    print(*i)

发表于 2024-09-29 21:00:31 回复(0)
n = int(input())
mat = [[0 for _ in range(n)]for _ in range(n)]

x , y = 0 , 0

if n % 2 == 0:
    for i in range(1,n**2+1):
        mat[x][y] = str(i)
        if x == n-1 and y % 2 == 0:
            y += 1
        elif x % 2 == 1 and y == n-1:
            x += 1
        elif x == 0 and y % 2 == 0 and y < n-1:
            y += 1
        elif x % 2 == 1 and y == 0 and x < n-1:
            x += 1
        elif (x + y) % 2 == 1:
            x += 1
            y -= 1
        elif (x + y) % 2 == 0:
            x -= 1
            y += 1

if n % 2 == 1:
    for i in range(1,n**2+1):
        mat[x][y] = str(i)
        if x == n-1 and y % 2 == 1:
            y += 1
        elif x % 2 == 0 and y == n-1:
            x += 1
        elif x == 0 and y % 2 == 0 and y < n-1:
            y += 1
        elif x % 2 == 1 and y == 0 and x < n-1:
            x += 1
        elif (x + y) % 2 == 1:
            x += 1
            y -= 1
        elif (x + y) % 2 == 0:
            x -= 1
            y += 1

for i in mat:
    print(" ".join(i))
发表于 2023-05-24 23:18:03 回复(0)