一年后我记起了我的问题并回来回答我自己的问题,因为我现在好一点了。这是我的解决方案。
def findNeighbors(gameMap,selectedRow,selectedColumn):
finalNeighbors = [] #the list that we will store final state of neighbor list
newNeighbors = [] #the list that we will store the new neighbors in every loop
newNeighborsClone = [] #the list that we will traverse inside after clearing the new neighbor list
newNeighbors.append([selectedRow,selectedColumn]) #we already have a known neighbor which is chosed one
selectedNumber = gameMap[selectedRow][selectedColumn]
print("Selected number = " + str(selectedNumber))
while newNeighbors: #while newNeighbors list has an element inside
finalNeighbors = finalNeighbors + newNeighbors #add every new neighbor to main neighbor list
newNeighborsClone = newNeighbors[::] #clone the new neighbors list
newNeighbors = [] #clearing the new neighbors list
for row,column in newNeighborsClone:
if row == 0: #if we're at peak we only need to look for down
if gameMap[row+1][column] == selectedNumber and [row+1,column] not in finalNeighbors: #and to prevent infinite loops, we have to check if its already in final neighbors list
newNeighbors.append([row+1,column])
elif row == (len(gameMap)-1): #if we're at the bottom we only need to look for up
if gameMap[row-1][column] == selectedNumber and [row-1,column] not in finalNeighbors:
newNeighbors.append([row-1,column])
else: #if we're somewhere at middle we have to look up and down
if gameMap[row+1][column] == selectedNumber and [row+1,column] not in finalNeighbors:
newNeighbors.append([row+1,column])
if gameMap[row-1][column] == selectedNumber and [row-1,column] not in finalNeighbors:
newNeighbors.append([row-1,column])
if column == 0: #if we're at the left side we only need to look for right
if gameMap[row][column+1] == selectedNumber and [row,column+1] not in finalNeighbors:
newNeighbors.append([row,column+1])
elif column == (len(gameMap[0])-1): #if we're at the right side we only need to look for left
if gameMap[row][column-1] == selectedNumber and [row,column-1] not in finalNeighbors:
newNeighbors.append([row,column-1])
else: #if we're somewhere at middle
if gameMap[row][column+1] == selectedNumber and [row,column+1] not in finalNeighbors:
newNeighbors.append([row,column+1])
if gameMap[row][column-1] == selectedNumber and [row,column-1] not in finalNeighbors:
newNeighbors.append([row,column-1])
finalNeighbors = deleteDuplicates(finalNeighbors) #Even after all of if elses, there can be still duplicated elements. Better removing them
return finalNeighbors
我无法将整个代码复制到这里,我不知道为什么。但这里是分配来完成这项工作的功能。我可以只使用 try except 块而不是所有这些 if else,但是在该分配中禁止使用 try except。所以我不得不这样做。您可以只检查 try 块中的所有四个方面,而不是那么多 ifs