日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python真題案例之蛇形數組詳解_python

作者:酷爾。 ? 更新時間: 2022-05-07 編程語言

問題描述??

輸入一個正整數n

在n*n的方陣內填入1,2,3,4…n*n,要求填成蛇形。(回旋的向中間收斂)

樣例輸入:

4

樣例輸出:

不必嚴格按照格式輸出,

問題分析??

蛇形填數,目的是為了考驗我們對數組索引的熟悉情況,觀察可知需要從右上角開始遍歷 先向下等碰到了下限左轉然后向上然后右轉,一直遍歷到最中心。這里需要對邊界進行判斷 我們對邊界判斷的時候需要有一個緩沖空間也就是說先判斷下一位置再賦值。 (如果先賦值再判斷,想往回走的話很麻煩),還有一點就是定住二維數組的一行或一列 移動另外的索引。由此我們可以寫出以下代碼。

代碼實現??

老規矩先上運行結果:

有了上面的思路后我們還可以進行逆時針的蛇形數組。

使用定一移一的思想我們還可以對數組進行旋轉。

蛇形數組源碼

import sys


def sn1(n):
    arr=[]
    for i in range(n):
        arr.append([0]*n)

    row=0
    col=n-1
    arr[row][col]=1

    i=1
    while i-1 and (not arr[row][col-1]):
            arr[row][col-1]=i+1
            col-=1
            i+=1
        while row-1>-1 and (not arr[row-1][col]):
            arr[row-1][col]=i+1
            row-=1
            i+=1
        while col+1-1 and not(arr[row][col-1])):
            arr[row][col-1]=i+1
            i+=1
            col-=1
        while(row+1-1 and not(arr[row-1][col])):
            arr[row-1][col]=i+1
            i+=1
            row-=1
    for i in range(n):
        flag=True
        for j in range(n):
            if flag:
                print(arr[i][j],end="")
                flag=False
            else:
                print("\t",arr[i][j],end="",sep="")
        print()

    


if __name__=="__main__":
    n=int(input())
    print("蛇形數組如下(順時針):")
    sn1(n)
    print("蛇形數組如下(逆時針):")
    sn2(n)

旋轉數組源碼

'''
大家都學習過矩陣,今天呢咱們將n*n類型的字符矩陣進行向左的90°旋轉
'''
#生成全為零的矩陣
arr=[]
n=int(input())
for i in range(n):
    arr.append([0]*n)

#蛇形矩陣

row=0
col=n-1
arr[row][col]=i=1
while i=0 and not arr[row][col-1]:
        arr[row][col-1]=i+1
        i+=1
        col-=1
    while row-1>=0 and not arr[row-1][col]:
        arr[row-1][col]=i+1
        i+=1
        row-=1
    while col+1

原文鏈接:https://blog.csdn.net/apple_51931783/article/details/123215979

欄目分類
最近更新