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 : 优化效率
原文:https://www.cnblogs.com/zhuangyao/p/12660472.html