-
Hajipur, Bihar, 844101
A Graph is a non-linear data structure that represents relationships between pairs of elements (called nodes or vertices) using edges.
Graphs can be:
Directed or Undirected
Weighted or Unweighted
Term | Meaning |
---|---|
Vertex | A node in the graph |
Edge | A connection between two vertices |
Adjacent | Two vertices connected by an edge |
Path | A sequence of vertices connected by edges |
Degree | Number of edges connected to a node |
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': ['F'],
'E': [],
'F': []
}
vertices = ['A', 'B', 'C']
matrix = [
[0, 1, 1],
[0, 0, 0],
[0, 0, 0]
]
def dfs(graph, node, visited):
if node not in visited:
print(node)
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
visited = set()
dfs(graph, 'A', visited)
✅ Output:
A
B
D
F
C
E
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex)
visited.add(vertex)
queue.extend(graph[vertex])
bfs(graph, 'A')
✅ Output:
A
B
C
D
E
F
Directed: Edges have direction → (A → B
)
Undirected: Edges go both ways (A — B
)
Social networks (users connected to users)
Maps and navigation (cities connected by roads)
Web crawlers (pages connected via links)
Network routing
AI pathfinding (games, robotics)
Q1. Write a Python program to create an undirected graph with 5 nodes using an adjacency list.
Q2. Write a Python program to implement a function to add new vertices to the graph.
Q3. Write a Python program to traverse the graph using Depth-First Search (DFS).
Q4. Write a Python program to traverse the graph using Breadth-First Search (BFS).
Q5. Write a Python program to count the number of connections (edges) for a given node.
Q6. Write a Python program to check if two nodes are connected directly.
Q7. Write a Python program to list all paths between two nodes using recursion or DFS.
Q8. Write a Python program to convert an adjacency list into an adjacency matrix.
Q9. Write a Python program to mark and print all visited nodes during a DFS traversal.
Q10. Write a Python program to create a weighted undirected graph using a dictionary of dictionaries or a tuple-based structure.
Q1: What does a graph consist of?
Q2: What type of graph uses arrows to represent edges?
Q3: Which search visits a node's neighbors first?
Q4: What data structure is commonly used for BFS?
Q5: What is the degree of a vertex?
Q6: In DFS, which structure is used internally?
Q7: Which Python data structure best represents an adjacency list?
Q8: Which type of graph is commonly used to represent road networks?
Q9: How many edges can a complete graph with n vertices have?
Q10: Which of the following is a real-world graph example?