Python修改二維列表(二維數組)中內容

用Python寫了一個BFS, 出了bug瘋狂檢查邏輯,並沒有錯
然後發現修改的vis數組出現了問題。

我定義的vis數組

vis = [n*[0]]*n

執行

vis[0][0]=1
#output:
# [[1,0],[1,0]]

原因是list的淺拷貝問題

list * n—>n shallow copies of list concatenated
n個list的淺拷貝的連接
修改其中的任何一個元素會改變整個列表

改寫爲循環賦值即可

vis = [([0]*n) for i in range(n)]

我的BFS代碼如下:

import queue
print("Please input the size of the square:")
n = int(input())
map_ = [([0]*n) for i in range(n)] #創建地圖
vis = [([0]*n) for i in range(n)] #訪問標記
front = [([0]*n) for i in range(n)] #路徑
s,t = [0,0],[n-1,n-1] #初始化貓(s)鼠(t)位置
xPos = [1,0,-1,0] # x座標方向
yPos = [0,1,0,-1] # y座標方向


def bfs(x,y):
    q = queue.Queue()
    q.put([x,y])
    vis[x][y]=1
    while q.qsize() != 0:
        now = q.get()
        if now == [n-1,n-1]:
            return
        for i in range(0,4):
            xx = now[0] + xPos[i]
            yy = now[1] + yPos[i]
            if xx<0 or xx>n-1 or yy<0 or yy>n-1:
                continue
            elif map_[xx][yy] == 1 or vis[xx][yy]==1:
                continue
            else:
                q.put([xx,yy])
                vis[xx][yy]=1
                front[xx][yy]=now # 記錄上一次的位置
    return

def printRoad():
    q = queue.LifoQueue() #棧
    now=[n-1,n-1]
    while now != [0,0]:
        # print(now)
        q.put(now)
        now = front[now[0]][now[1]]
    print("The road:")
    while q.qsize():
        temp = q.get()
        print(temp)

for i in range(n):
    map_[i] = input().split(" ")

map_[0][0]='S' #標記貓位置
map_[n-1][n-1]='T' #標記鼠位置
# print(vis)
# print(map_[1][0])
# print(vis[1][0])

bfs(0,0)
printRoad()

# 輸入
# S 代表起點(貓的位置)T代表終點(鼠的位置)
# 1 代表有路障, 0代表沒有
'''
input: 
6
S 0 0 0 0 0
0 0 0 0 1 0
0 1 0 0 1 1
0 1 0 0 0 0
0 1 0 1 0 0
0 0 0 0 0 T
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章