首页 > 试题广场 >

螺旋数

[编程题]螺旋数
  • 热度指数:587 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
下图是一个4阶的螺旋数阵:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
数字从1开始,沿着顺时针方向依次填满整个矩阵。
现在给你矩阵的规模n,请你输出n阶螺旋数阵。

输入描述:
输入包含多组数据,每组数据包含一个正整数n(1≤n≤20)。


输出描述:
对应每组数据,输出相应的螺旋数阵。

每组数据之后输出一个空行作为分隔。
示例1

输入

3
4

输出

1 2 3
8 9 4
7 6 5

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

python solution

import sys


def generateMatrix(n):
    res = [[0 for i in range(n)] for j in range(n)]
    count = 1
    rowIndex1 = 0
    rowIndex2 = n - 1
    colIndex1 = n - 1
    colIndex2 = 0
    rowNum = n
    while rowNum >= 1:
        for i in range(colIndex2, colIndex1 + 1):
            res[rowIndex1][i] = count
            count += 1
        rowIndex1 += 1

        for i in range(rowIndex1, rowIndex2 + 1):
            res[i][colIndex1] = count
            count += 1
        colIndex1 -= 1

        for i in range(colIndex1, colIndex2 - 1, -1):
            res[rowIndex2][i] = count
            count += 1
        rowIndex2 -= 1

        for i in range(rowIndex2, rowIndex1 - 1, -1):
            res[i][colIndex2] = count
            count += 1
        colIndex2 += 1
        rowNum -= 2
    return res


for i in sys.stdin.readlines():
    matrix = generateMatrix(int(i))
    for line in matrix:
        print(" ".join(map(str, line)))
    print()
发表于 2017-11-17 11:05:20 回复(0)