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.
defconnectedCell(matrix):defdfs(matrix,visited,i,j):# Stack for DFSstack=[(i,j)]count=0whilestack:x,y=stack.pop()ifnot(0<=x<nand0<=y<m)orvisited[x][y]ormatrix[x][y]==0:continuevisited[x][y]=Truecount+=1# Check all 8 possible directionsfordx,dyin[(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:stack.append((x+dx,y+dy))returncountn=len(matrix)m=len(matrix[0])visited=[[False]*mfor_inrange(n)]max_region=0foriinrange(n):forjinrange(m):ifmatrix[i][j]==1andnotvisited[i][j]:size_of_region=dfs(matrix,visited,i,j)max_region=max(max_region,size_of_region)returnmax_region
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 →