We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
fromcollectionsimportdequedefconnectedCell(matrix):maxRegion=-1seen=set()start=findUnseen(matrix,seen)offset=[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]whilestart:# perfrom bfs from given starting pointregionArea=1frontier=deque()frontier.append(start)whilefrontier:curr=frontier.popleft()neighbors=[]forofinoffset:i=curr[0]+of[0]j=curr[1]+of[1]ifi>=0andi<len(matrix)andj>=0andj<len(matrix[0]):neighbors.append((i,j))ifcurrnotinseen:regionArea+=1seen.add(curr)forneighborinneighbors:i=neighbor[0]j=neighbor[1]ifmatrix[i][j]==1and(i,j)notinseen:frontier.append((i,j))maxRegion=max(regionArea,maxRegion)start=findUnseen(matrix,seen)returnmaxRegiondeffindUnseen(matrix,seen):foriinrange(len(matrix)):forjinrange(len(matrix[0])):ifmatrix[i][j]==1and(i,j)notinseen:seen.add((i,j))return(i,j)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Connected Cells in a Grid
You are viewing a single comment's thread. Return to all comments →