我在 python 中有以下遞回函式:
def _floodfill(matrix, x, y, counter):
if matrix[x][y] != 9:
matrix[x][y] = 9
counter = 1
# recursively invoke flood fill on all surrounding cells:
if x > 0:
counter = int(_floodfill(matrix, x - 1, y, counter) or 0)
if x < len(matrix) - 1:
counter = int(_floodfill(matrix, x 1, y, counter) or 0)
if y > 0:
counter = int(_floodfill(matrix, x, y - 1, counter) or 0)
if y < len(matrix[0]) - 1:
counter = int(_floodfill(matrix, x, y 1, counter) or 0)
return counter
我想計算這個函式被呼叫的頻率,分別計算該區域中有多少個數字!= 9。使用以下矩陣并呼叫函式,例如:_floodfill(matrix,1,1,0)函式應回傳 2:
[[9,9,9],
[9,2,9],
[9,3,9],
[9,9,9]]
我的代碼有什么問題?
編輯 我認為該函式更易讀,如下所示:
def _floodfill(matrix, x, y, counter):
if matrix[x][y] != 9:
matrix[x][y] = 9
counter = 1
# recursively invoke flood fill on all surrounding cells:
if x > 0:
counter = _floodfill(matrix, x - 1, y, counter)
if x < len(matrix) - 1:
counter = _floodfill(matrix, x 1, y, counter)
if y > 0:
counter = _floodfill(matrix, x, y - 1, counter)
if y < len(matrix[0]) - 1:
counter = _floodfill(matrix, x, y 1, counter)
return counter
else:
return 0
uj5u.com熱心網友回復:
三注:
您不需要傳遞
counter給您的遞回呼叫。他們需要它做什么?counter保存先前訪問過的單元格數量。您的遞回呼叫不需要知道您已經訪問了多少個單元格。該資訊反過來移動:您想要的是遞回呼叫來告訴您它們訪問了多少個單元格。如果 an
if/else中的所有分支都具有一致的return值,則撰寫函式并使用該函式會容易得多。如果函式有時回傳訪問單元格數,有時回傳None,使用起來會超級不方便;請注意您必須如何int(...) or 0在每次遞回呼叫后添加以解決該問題。您的矩陣存盤為串列串列的方式,對我來說,用 索引行
y和列x比其他方式更有意義。
def _floodfill(matrix, y, x):
if matrix[y][x] == 9:
return 0
else:
matrix[y][x] = 9
counter = 1
if x > 0:
counter = _floodfill(matrix, y, x - 1)
if x < len(matrix) - 1:
counter = _floodfill(matrix, y, x 1)
if y > 0:
counter = _floodfill(matrix, y - 1, x)
if y < len(matrix[0]) - 1:
counter = _floodfill(matrix, y 1, x)
return counter
mat = [
[9,9,9],
[9,2,9],
[9,3,9],
[9,9,9]
]
c = _floodfill(mat, 1, 1)
print(c)
print(mat)
# 2
# [[9, 9, 9], [9, 9, 9], [9, 9, 9], [9, 9, 9]]
uj5u.com熱心網友回復:
使用串列將計數器保存為 int 按值傳遞:
def _floodfill(matrix, x, y, counter):
if matrix[x][y] != 9:
matrix[x][y] = 9
counter[0] = 1
# recursively invoke flood fill on all surrounding cells:
if x > 0:
_floodfill(matrix, x - 1, y, counter)
if x < len(matrix) - 1:
_floodfill(matrix, x 1, y, counter)
if y > 0:
_floodfill(matrix, x, y - 1, counter)
if y < len(matrix[0]) - 1:
_floodfill(matrix, x, y 1, counter)
return counter
else:
return 0
_floodfill([[9,9,9],
[9,2,9],
[9,3,9],
[9,9,9]], 1, 1, [0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378866.html
