我正在尝试解决一个问题,我应该创建一个字体,该字典的坐标标记为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)
让我知道我在哪里做错了。
答案 0 :(得分:0)
我已经解决了我自己的问题。边缘情况存在一个问题,这就是为什么它不起作用。我使用它们的条件是错误的。
谢谢大家的帮助。