You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add the current element to the q and the visited set
While q is not empty, pop from the first element to check if the element satisfies certain condition
If it does, update to the q and the visited set
classSolution:
defnumIslands(self, grid: List[List[str]]) ->int:
visited=set()
R, C=len(grid), len(grid[0])
islands=0defbfs(r, c):
q=deque()
# Store current r, c in visited and qvisited.add((r, c))
q.append((r, c))
whileq:
qr, qc=q.popleft()
directions= [[1,0],[-1,0],[0,1],[0,-1]]
# Check the adjacent islandsfordr, dcindirections:
nr, nc=qr+dr, qc+dc# Check if new coordinate is within the index, is a land, and is not visitedif0<=nr<Rand0<=nc<Candgrid[nr][nc] =='1'and (nr, nc) notinvisited:
q.append((nr, nc))
visited.add((nr, nc))
forrinrange(R):
forcinrange(C):
# Search if the current item is a landifgrid[r][c] =='1'and (r, c) notinvisited:
bfs(r, c)
islands+=1returnislands
n: number of nodes
Time Complexity: O(n)
The text was updated successfully, but these errors were encountered:
BFS
n: number of nodes
Time Complexity: O(n)
The text was updated successfully, but these errors were encountered: