Python 停止洪水填充算法
我被洪水填充算法困住了:它会在“正常”不应该的某个时刻停止 情况是这样的:我有一个512*512像素的矩阵,值是50或100。50的值形成了一个正方形,我想在一个值为255的正方形中改变它(使用泛光填充算法)Python 停止洪水填充算法,python,flood-fill,Python,Flood Fill,我被洪水填充算法困住了:它会在“正常”不应该的某个时刻停止 情况是这样的:我有一个512*512像素的矩阵,值是50或100。50的值形成了一个正方形,我想在一个值为255的正方形中改变它(使用泛光填充算法) def FF(矩阵,x,y,h):#选择h问题位于此处: (x,y)=stack[0] # get the first element of the list stack.pop() # remove the *last* element 由于您获得了第一个元素,但删除了
def FF(矩阵,x,y,h):#选择h问题位于此处:
(x,y)=stack[0] # get the first element of the list
stack.pop() # remove the *last* element
由于您获得了第一个元素,但删除了最后一个元素,因此有可能(就像并且可能总是这样)不会对推送到堆栈上的所有元素求值
然而,你把它弄得太复杂了。简单地写下:
def FF(matrix,x,y,h): #h is chosen <=50
stack=[(x,y)]
m,n = matrix.shape
while stack:
x,y = stack.pop()
if 0 <= x < m and 0 <= y < n and matrix[x,y] <= h: # check bounds and height
matrix[x,y] = 255 # set the value
stack.append((x-1,y-1)) # add all directions to the stack, we check later
stack.append((x,y-1))
stack.append((x+1,y-1))
stack.append((x-1,y))
stack.append((x+1,y))
stack.append((x-1,y+1))
stack.append((x,y+1))
stack.append((x+1,y+1))
def FF(matrix,x,y,h):#选择h作为您的matrix[x-1,y]在测试代码后,它可以完美地工作,而且确实更简单。谢谢你@昆汀:我发现了你代码的问题,并重写了答案。
def FF(matrix,x,y,h): #h is chosen <=50
stack=[(x,y)]
m,n = matrix.shape
while stack:
x,y = stack.pop()
if 0 <= x < m and 0 <= y < n and matrix[x,y] <= h: # check bounds and height
matrix[x,y] = 255 # set the value
stack.append((x-1,y-1)) # add all directions to the stack, we check later
stack.append((x,y-1))
stack.append((x+1,y-1))
stack.append((x-1,y))
stack.append((x+1,y))
stack.append((x-1,y+1))
stack.append((x,y+1))
stack.append((x+1,y+1))