A graph is a non-linear data structure consisting of nodes (or vertices) and edges that connect pairs of nodes. Graphs are used to represent networks, such as social networks, communication networks, and more. They can be directed or undirected, weighted or unweighted.
function addEdge(graph, node1, node2):
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1) // For undirected graph
function dfs(graph, start, visited=set()):
if start not in visited:
print(start)
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
function bfs(graph, start):
queue = [start]
visited = set([start])
while queue:
vertex = queue.pop(0)
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)