我正在尝试使一个python dfs连接岛与递归。。。在
程序运行良好,但在某些情况下,会出现逻辑错误,导致输出不正确
例如
o o o
o x x
o o o the output is 1 which is correct.
但是,在其他情况下
^{pr2}$这是包含dfs函数的完整代码
row = int(input("Enter Row : "))
col = int(input("Enter Col : "))
# declare array baru namanya peta
peta = []
# array 2 dimensi
# Masukkin smua input ke array petas
for i in range(0,row):
line = input()
peta.append(line)
store = []
# declare array baru nama visited
visited = []
for i in range(0,row):
visited.append([])
# buat column di row i false smua
for j in range(0,col):
visited[i].append(False)
def dfs(i,j):
visited[i][j] = True
a = row-1
b = col-1
#peta[i][j] = store[a][b]
for i in range(i,row):
for j in range(j,col):
if(visited[i][j] == True):
return 1
else:
if(peta[i][j] == 'x' and visited[i][j] == False ):
#top left array
if(i == 0 or j == 0):
dfs(i+1,j+1)
dfs(i+1,j)
dfs(i,j+1)
#bottom left array
elif(i == a and j == 0):
dfs(i-1,j)
dfs(i-1,j+1)
dfs(i,j+1)
#top right array
elif(i == 0 and j == b):
dfs(i,j-1)
dfs(i+1,j-1)
dfs(i+1,j)
#bottom right array
elif(i == a and j == b):
dfs(i,j-1)
dfs(i-1,j-1)
dfs(i-1,j)
#west array
elif(i >= 1 and j == 0):
dfs(i-1,j)
dfs(i-1,j+1)
dfs(i+1,j)
dfs(i,j+1)
dfs(i+1,j+1)
#north array
elif(i==0 and j>=1):
dfs(i,j-1)
dfs(i+1,j-1)
dfs(i+1,j)
dfs(i,j+1)
dfs(i+1,j+1)
#east array
elif(i>=1 and j==b):
dfs(i-1,j)
dfs(i-1,j-1)
dfs(i,j-1)
dfs(i+1,j-1)
dfs(i+1,j)
#south array
elif(i==a and j>=1):
dfs(i,j-1)
dfs(i-1,j-1)
dfs(i-1,j)
dfs(i-1,j+1)
dfs(i,j+1)
#middle array
else:
dfs(i-1,j-1)
dfs(i-1,j)
dfs(i-1,j+1)
dfs(i,j-1)
dfs(i,j+1)
dfs(i+1,j-1)
dfs(i+1,j)
dfs(i+1,j+1)
else:
#peta[i][j] = 0
return 0
numberofisland = 0
for i in range(0,row):
for j in range(0,col):
if((peta[i][j] == 'x' and visited[i][j] == False)):
dfs(i,j)
numberofisland+=1
print(numberofisland)
在我看来,我的逻辑错误是我访问了两次被访问的节点,但是在我的数组中似乎没有错误。你能就我的错误在哪里提出一些建议吗?在
非常感谢您抽出时间,干杯
编辑:我已经根据社区的要求更新了完整的代码版本(如何调用函数、全局变量等)
代码中的某些内容没有意义:
1)如果您想从}或任何东西。在
dfs
函数返回一个值,这个值应该有一些意义,应该使用它。如果您只调用函数的副作用,那么您就可以return
而不加任何值。在本例中,dfs
函数的目的是更新visited
数组,因此不需要返回1
或{2)在图中进行深度优先搜索时,从一个节点开始,递归地访问其连接的节点。如果在
dfs
函数中有一个for循环,它访问了图形的大部分,忽略了连接,那么就不是在执行DFS。通常,您只需要在连接的节点上递归调用dfs
函数。在3)现在看来,函数在进行任何递归调用之前总是返回
1
。在还要注意以下Python代码的良好实践:
1)避免像
if expression == True:
这样的结构。而是使用if expression:
。也不要使用if expression == False
,而是使用if not expression
。在2)避免在
if
和elif
子句中使用条件表达式的括号,这不是必需的,不像C或Java。例如,使用elif (a == b):
代替elif (a == b):
。在3)在函数的顶部添加一个docstring,以描述该函数的作用(参见下面我的代码以获取示例)。在
据我所知,每次调用
dfs
函数时,都需要访问构成一个岛的所有连接的x。可以使用以下代码执行此操作:相关问题 更多 >
编程相关推荐