Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BFS & DFS Pseudocode #44

Open
sophryu99 opened this issue Jan 24, 2023 · 0 comments
Open

BFS & DFS Pseudocode #44

sophryu99 opened this issue Jan 24, 2023 · 0 comments

Comments

@sophryu99
Copy link
Owner

sophryu99 commented Jan 24, 2023

BFS

  1. Initialize a queue and visited set
  2. Add the current element to the q and the visited set
  3. While q is not empty, pop from the first element to check if the element satisfies certain condition
  4. If it does, update to the q and the visited set
 class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        visited = set()
        R, C = len(grid), len(grid[0])
        islands = 0

        def bfs(r, c):
            q = deque()
            # Store current r, c in visited and q
            visited.add((r, c))
            q.append((r, c))

            while q:
                qr, qc = q.popleft()
                directions = [[1,0],[-1,0],[0,1],[0,-1]]

                # Check the adjacent islands
                for dr, dc in directions:
                    nr, nc = qr + dr, qc + dc
                    # Check if new coordinate is within the index, is a land, and is not visited
                    if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == '1' and (nr, nc) not in visited:
                        q.append((nr, nc))
                        visited.add((nr, nc))

        for r in range(R):
            for c in range(C):
                # Search if the current item is a land
                if grid[r][c] == '1' and (r, c) not in visited:
                    bfs(r, c)
                    islands += 1

        return islands

n: number of nodes
Time Complexity: O(n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant