from collections import deque


def breadth_first_distances(
    graph: dict[str, list[str]], start: str
) -> dict[str, int]:
    """Return unweighted shortest distances from one vertex.

    Args:
        graph: Adjacency lists with every neighbor also present as a key.
        start: Vertex from which to search.

    Returns:
        Distances for reachable vertices, including zero for start.

    Raises:
        ValueError: If start is not a graph vertex.
    """
    if start not in graph:
        raise ValueError("start must be a graph vertex")
    distances = {start: 0}
    frontier = deque([start])
    while frontier:
        vertex = frontier.popleft()
        for neighbor in graph[vertex]:
            if neighbor not in distances:
                distances[neighbor] = distances[vertex] + 1
                frontier.append(neighbor)
    return distances


graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"],
    "E": [],
}
print("Distances from A:", breadth_first_distances(graph, "A"))
print("Distances from E:", breadth_first_distances(graph, "E"))

distances = {"A": 0}
frontier = deque(["A"])
print("Initial queue:", list(frontier))
while frontier:
    vertex = frontier.popleft()
    for neighbor in graph[vertex]:
        if neighbor not in distances:
            distances[neighbor] = distances[vertex] + 1
            frontier.append(neighbor)
    print("Expanded", vertex, "queue", list(frontier),
          "discovered", list(distances))

def connected_components(graph: dict[str, list[str]]) -> list[list[str]]:
    """Return DFS components of an undirected graph.

    Args:
        graph: Complete symmetric adjacency lists for an undirected graph.

    Returns:
        Components in dictionary order, with DFS expansion within each one.
    """
    visited: set[str] = set()
    components: list[list[str]] = []
    for start in graph:
        if start in visited:
            continue
        visited.add(start)
        stack = [start]
        component: list[str] = []
        while stack:
            vertex = stack.pop()
            component.append(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    stack.append(neighbor)
        components.append(component)
    return components


print("DFS components:", connected_components(graph))
assert connected_components({}) == []
assert connected_components({"A": []}) == [["A"]]
assert breadth_first_distances({"A": ["A"]}, "A") == {"A": 0}
assert breadth_first_distances(graph, "A")["D"] == 2
print("The empty, isolated, self-loop, and cycle cases pass.")

def nearest_source_distances(grid: list[str]) -> list[list[int]]:
    """Find grid distances from several sources through unit-cost moves.

    Args:
        grid: Equal-length, nonempty rows containing S, ., or #. An empty
            list represents an empty grid. The input remains unchanged.

    Returns:
        Nearest-source distances, with -1 for unreachable cells and -2 for
        walls. An empty grid produces an empty list.

    Raises:
        ValueError: If rows are empty, unequal, or contain another character.
    """
    if not grid:
        return []
    width = len(grid[0])
    if width == 0 or any(len(row) != width for row in grid):
        raise ValueError("grid rows must be nonempty and equal in length")
    if any(character not in "S.#" for row in grid for character in row):
        raise ValueError("grid cells must be S, ., or #")
    distances = [[-1] * width for _ in grid]
    frontier = deque()
    for row, cells in enumerate(grid):
        for column, character in enumerate(cells):
            if character == "#":
                distances[row][column] = -2
            elif character == "S":
                distances[row][column] = 0
                frontier.append((row, column))
    while frontier:
        row, column = frontier.popleft()
        for row_step, column_step in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            next_row = row + row_step
            next_column = column + column_step
            if not (0 <= next_row < len(grid) and 0 <= next_column < width):
                continue
            if distances[next_row][next_column] != -1:
                continue
            distances[next_row][next_column] = distances[row][column] + 1
            frontier.append((next_row, next_column))
    return distances


room_grid = ["S..#.", ".#...", "...#S"]
print("Distance to the nearest source:")
for distance_row in nearest_source_distances(room_grid):
    print(distance_row)
print("Walls and unreachable cells:")
for distance_row in nearest_source_distances(["S#.", "###", "..S"]):
    print(distance_row)

assert nearest_source_distances([]) == []
assert nearest_source_distances(["S"]) == [[0]]
assert nearest_source_distances(["."]) == [[-1]]
assert nearest_source_distances(["#"]) == [[-2]]
assert nearest_source_distances(["S.S"]) == [[0, 1, 0]]
assert nearest_source_distances(["S#."]) == [[0, -2, -1]]
assert room_grid == ["S..#.", ".#...", "...#S"]
print("Empty, isolated, blocked, and multiple-source grid checks pass.")
