岛屿问题
Posted zhuangyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了岛屿问题相关的知识,希望对你有一定的参考价值。
python3:
lst = [] for q in range(4): lst.append(list(map(eval, list(input(""))))) mark = 2 print(lst[3][4]) dict0 = {} #递归标记周边陆地 def markAround(x,y,mark): if (x+1)<=3 and lst[x+1][y] ==1: lst[x + 1][y] = mark dict0[mark] = dict0[mark]+2 markAround(x+1,y,mark) if (x-1)>=0 and lst[x-1][y] ==1: lst[x - 1][y] = mark dict0[mark] = dict0[mark] + 2 markAround(x-1,y,mark) if (y+1)<=4 and lst[x][y+1] ==1: lst[x][y+1] = mark dict0[mark] = dict0[mark] + 2 markAround(x,y+1,mark) if (y-1)>=0 and lst[x][y-1] ==1: lst[x][y-1] = mark dict0[mark] = dict0[mark] + 2 markAround(x,y-1,mark) for x in range(4): for y in range(5): #若找到一块岛屿,就++count if lst[x][y]==1: lst[x][y] = mark dict0[mark] = 2 markAround(x,y,mark) mark += 1 print(lst) # for i in range(4): # for j in range(5): # if lst[i][j]==0: # continue # if lst[i][j] in dict0.keys(): # dict0[lst[i][j]] = dict0[lst[i][j]] + 2 # if lst[i][j] not in dict0.keys(): # dict0[lst[i][j]] = 2 print(dict0) print(len(dict0))
TODO : 优化效率
以上是关于岛屿问题的主要内容,如果未能解决你的问题,请参考以下文章