SEP- AIA

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 . . .

5.

 
  
 
 
 5. Write a program to traverse a small hardcoded graph (e.g., Node A connected to B and C) using
the Depth First Search logic.

# 5. Python Program to Traverse a Graph Using DFS

### Program

```python
# Depth First Search (DFS)

# Hardcoded graph
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': [],
    'F': []
}

visited = set()

def DFS(node):
    if node not in visited:
        print(node, end=" ")
        visited.add(node)

        for neighbour in graph[node]:
            DFS(neighbour)

# Starting node
print("DFS Traversal:")
DFS('A')
```

### Output

```text
DFS Traversal:
A B D E C F
```

### Explanation

* The graph is represented using a **dictionary**.
* Node `A` is connected to `B` and `C`.
* DFS starts from node `A`.
* It visits a node and then recursively explores its unvisited neighbours.
* The `visited` set ensures that a node is not visited more than once.

### Graph Representation

```text
        A
       / \
      B   C
     / \   \
    D   E   F
```