【发布时间】:2017-06-13 17:43:40
【问题描述】:
我正在尝试解决一个问题,我应该创建一个字典,该字典具有标记为 1 的节点的坐标及其也是一个 (1) 的邻居。这基本上是我需要创建的邻接列表以便在其上实现 BFS/DFS。
我已经尝试过使用 setdefault() 方法和 get() 方法。我之前因为一些问题这样做过,但我不记得了。
这是我为此编写的代码。
n,m=input().split()
n=int(n)
m=int(m)
#q=int(q)
"""User Input Done"""
square=[[0 for i in range(n)] for j in range(m)]
neighbour_dictionary={}
#neighbour_dictionary.setdefault(,[])
for i in range(n):
for j in range(m):
number=int(input("Enter a number"))
square[i][j]=number
"""Get Initial Number of Nations(1)"""
nation_count=0
for i in range(0,n):
for j in range(0,m):
if square[i][j]==1:
try:
if square[i][j+1]==1 and (j+1)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i,j)].setdefault([i,j],[]).append((i,j+1))
except KeyError:
neighbour_dictionary[(i,j)]=[(i,j+1)]
except IndexError:
pass
#print("c1")
#print((i,j),(i,j+1))
try:
if square[i+1][j+1]==1 and (i+1)>0 and (j+1)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i,j)].setdefault([i,j],[]).append((i+1,j+1))
except KeyError:
neighbour_dictionary[(i, j)] = [(i+1, j+1)]
except IndexError:
pass
#print("c2")
#print((i,j),(i+1,j+1))
try:
if square[i+1][j-1]==1 and (i+1)>0 and (j-1)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i, j)].setdefault([i,j],[]).append((i+1, j-1))
except KeyError:
neighbour_dictionary[(i, j)] = [(i+1,j-1)]
except IndexError:
pass
#print("c3")
#print((i,j),(i+1,j-1))
try:
if square[i][j-1]==1 and (j-1)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i, j)].setdefault([i,j],[]).append((i, j-1))
except KeyError:
neighbour_dictionary[(i, j)] = [(i, j + 1)]
except IndexError:
pass
#print("c4")
#print((i,j),(i,j-1))
try:
if square[i-1][j]==1 and (i-1)>0 and (j)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i, j)].setdefault([i,j],[]).append((i-1, j))
except KeyError:
neighbour_dictionary[(i, j)] = [(i-1, j)]
except IndexError:
pass
#print('c5')
try:
if square[i+1][j]==1 and (i+1)>0 and (j)>0 and (i<n) and (j<m):
try:
neighbour_dictionary[(i, j)].setdefault([i,j],[]).append((i+1, j))
except KeyError:
neighbour_dictionary[(i, j)] = [(i+1, j)]
except IndexError:
pass
#print("c6")
#print((i,j),(i+1,j))
try:
if square[i-1][j-1]==1 and (i-1)>0 and (j-1)>0:
try:
neighbour_dictionary[(i, j)].setdefault([i,j],[]).append((i-1, j-1))
except KeyError:
neighbour_dictionary[(i, j)] = [(i-1, j-1)]
except IndexError:
pass
#print("c7")
#print((i,j),(i-1,j-1))
print(neighbour_dictionary)
请告诉我我到底哪里做错了。
【问题讨论】:
-
@Srini 你能帮我解决这个问题吗?
-
无忌我不知道对不起
标签: python-3.x dictionary matrix breadth-first-search