我正在尝试解决一个检查任务,您必须计算给定二维数组中的岛数,其中岛定义为水平、对角线或垂直连接的一组“1”(http:/ /www.checkio.org/mission/task/info/calculate-islands/python-3/)。我写的代码应该首先从搜索空间中删除一个位置(我不知道我是否使用了正确的词,我对算法一无所知)如果该位置的数字是 0。问题是代码只删除了一些上面有数字 0 的位置,而不是其他有 0 的位置。这是代码:
def checkio(data):
result = ''
count = 0
boo = True
searchspace = []
specificsearchspace = []
def search(y,x):
result = ''
count = 0
if data[y][x] == 0:
searchspace.remove([y,x])
if data[y][x] == 1:
specificsearchspace.extend([[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]])
for i in specificsearchspace:
if data[i[0]][i[1]] == 0:
searchspace.remove(i)
specificsearchspace.remove(i)
if data[i[0]][i[1]] == 1:
searchspace.remove(i)
specificsearchspace.remove(i)
count += 1
search(i[0],i[1])
result += str(count) + ','
return result
for y in range(len(data)):
for x in range(len(data[y])):
searchspace.append([y,x])
print searchspace
for f in searchspace:
print search(f[0],f[1])
print searchspace
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]) == [1, 3], "1st example"
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]) == [5], "2nd example"
assert checkio([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]) == [2, 3, 3, 4], "3rd example"
输出是这样的:
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
None
None
None
None
1,
None
None
None
None
None
[[0, 1], [0, 3], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [4, 0], [4, 2], [4, 4]]