我是新手,对Python和编程一般不太熟悉。我写了一个函数,可以搜索数组中相邻的元素,并查找值在0.05之内的元素,这有点像泛洪算法。唯一的区别是,在计算函数运行次数(我认为这也会告诉我找到多少个元素)时,我做了一些愚蠢的事情,所以我的计数器值是错误的。代码在查找0.05范围内的相邻元素方面是有效的,只是计数有些问题。
def floodcount (x,y,array,value,count=0): #akin to a bucket fill in paint, finds the area instead
nrows = len(array)-1 #rows of the image
ncols = len(array[0])-1 #columns of the image
diff = array[x][y] - value
if (diff < 0.00) or (diff > 0.05): # the base case, finding a diff more than 0.05 or less than 0 is like finding a boundary
return 0
count = count +1
print 'count1 ',count
array[x][y] = -5 # so we do no calculate this pixel again
#print "[",x,",",y,"]"
if x > 0:
#print '1'# if not the first elemnet then can go back, this makes sure that x is within the array all the time
floodcount (x-1,y,array,value,count)
if y > 0:
#print '2'
floodcount (x,y-1,array,value,count)
if x < nrows:
#print '3'
floodcount (x+1,y,array,value,count)
if y < ncols:
#print '4'
floodcount (x,y+1,array,value,count)
if x > 0 and y > 0:
#print '5'
floodcount (x-1,y-1,array,value,count)
if x < nrows and y < ncols:
#print '6'
floodcount (x+1,y+1,array,value,count)
if x <nrows and y > 0:
#print '7'
floodcount (x+1,y-1,array,value,count)
if x > 0 and y < ncols:
#print '8'
floodcount (x-1,y+1,array,value,count)
print 'count2 ',count
return count
因此,对于一个测试用例
数组 = [[5,1,1,3,4],[4,5,6,2,5],[5,8,5,5,9]] x=0 和 y=0
输出
count1 1 count1 2 count1 3 count1 4 count1 5 count2 5 count2 4 count2 3 count1 3 count2 3 count2 2 count2 1
正如你所看到的,有些可疑 :P 有人能指出我做错了什么吗?任何帮助将不胜感激。