1. 程式人生 > >【leetcode】827. Making A Large Island

【leetcode】827. Making A Large Island

clas rip 代碼 nds inf ima xrange des 進行

題目如下:

技術分享圖片

解題思路:這個題目可以進行拆分成幾個子問題。第一,求出island的數量,其實就是 200. Number of Islands,這個很簡單,DFS或者BFS都能搞定;第二,除了求出island的數量之外,還要求出每個island包括的1的數量,這個也不難,在DFS或者BFS的過程中計數即可;第三,遍歷grid中所有的0,判斷每個0的上下左右分別連接了幾個不同的island,並將連接的所有island的所有1的數量求和,再加上本身的1(0變來的)即是這個0變成1可以得到的large island,最後,求出所有0的最大的large island即可。

代碼如下:

class Solution(object):
    
def largestIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ for i in grid: i.append(#) i.insert(0,#) grid.append([# for i in grid[0]]) grid.insert(0,[# for i in grid[0]]) visit = []
for i in grid: visit.append([0 for x in i]) queue = [] l = [0] area = 1 num = 1 for i in xrange(1,len(grid)): for j in xrange(1,len(grid[i])): if grid[i][j] == # or grid[i][j] == 0: continue if
visit[i][j] != 0: continue queue.append((i,j,area)) visit[i][j] = area while len(queue) > 0: x,y,a = queue.pop(0) # a為island的編號,用來記錄一個有幾個island if grid[x+1][y] == 1 and visit[x+1][y] == 0: num += 1 queue.append((x+1,y,a)) visit[x + 1][y] = a if grid[x-1][y] == 1 and visit[x-1][y] == 0: num += 1 queue.append((x-1,y,a)) visit[x - 1][y] = a if grid[x][y+1] == 1 and visit[x][y+1] == 0: num += 1 queue.append((x,y+1,a)) visit[x][y + 1] = a if grid[x][y-1] == 1 and visit[x][y-1] == 0: num += 1 queue.append((x,y-1,a)) visit[x][y - 1] = a area += 1 l.append(num) #l為每個island的1的數量 num = 1 res = 0 for i in l: if res < i: res = i #print visit,l for i in xrange(1,len(grid)): for j in xrange(1,len(grid[i])): if grid[i][j] == 0: count = 1 al = [] if grid[i+1][j] == 1: if visit[i+1][j] not in al: count += l[visit[i+1][j]] al.append(visit[i+1][j]) if grid[i-1][j] == 1: if visit[i-1][j] not in al: count += l[visit[i-1][j]] al.append(visit[i-1][j]) if grid[i][j+1] == 1: if visit[i][j+1] not in al: count += l[visit[i][j+1]] al.append(visit[i][j+1]) if grid[i][j-1] == 1: if visit[i][j-1] not in al: count += l[visit[i][j-1]] al.append(visit[i][j-1]) if res < count: res = count return res

【leetcode】827. Making A Large Island