私は一般的にはPythonとプログラミングの初心者です。私は配列内の隣接する要素を検索し、floodfillアルゴリズムのように互いに0.05以内の値を持つ関数を探す関数を書いています。唯一の違いは、関数が何回実行されたかを数えることになると私は何か愚かなことをしていることです(私が考えている要素の数がわかります)ので、カウンタ値が間違っています。このコードは、互いに0.05以内で隣接する要素を見つけることになります。ちょうどカウントが面白いです。テストケース再帰関数のカウンタ
配列= [5,1,1,3,4]、[4,5,6,2,5]、[5,8,5ためだから
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,9] X = 0、Y = 0
OUTPUT
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 は私が間違っているの何誰を指摘することはできますか?どんな助けもありがとう。私の解明(ここでは下)正確に適切ではありません。あなたが取得
実際には行と列の数が格納されていないため、nrowsとncolsの名前を変更する必要があると思います(回答しようとすると混乱してしまいます)。初期化から-1を削除し、ifステートメントロジックを変更します。 – colithium