Graphs Practice Questions
Graphs Practice Questions
1. Build a graph class for a simple graph that uses adjacency list representation. Simple means that between
any two vertices in a graph G, there will be at most one edge.
2. For each vertex you need to remember the vertex id, name, marker (for visited), list of adjacent nodes.
Make a class for vertex. A vertex will have following attributes:
3. Keep an array of vertices in graph class, an integer to store the number of vertices and a bool for
directed/undirected. Do not keep a linked list of vertices. Because that will increase the time complexity of
graph functions like DFS and BFS .
d. AddEdge(vertexname1 , vertexname2 )
i. Input the names of two vertices and add an edge between them
ii. Note in this case you will have to search the vertices with given name
e. AddVertex
i. The function input vertex name from the user
ii. The function assigns next available free vertex id to the vertex
iii. Set visited to false
iv. Set Adjacent nodes to Null. (because we will add adjacent nodes information using add
edge function
f. ResetMarker
i. It will reset the boolean marker in each vertex to zero.
g. Print the graph in Depth First order
i. print the name of the vertices in order they are visited in DFS
ii. Run the DFS
h. Print the graph in Breadth First order (print the name of the vertices in order they are visited in
DFS)
i. Print the DFS Spanning tree (just output the list of edges in the tree).
j. Print BFS Spanning tree (just output the list of edges in the tree).
k. Computes and return the square of a graph. The square of a graph G(V, E) is the graph G2 (V, E2)
such that (u, v) Є E2 if and only G contains a path with at most two edges between u and v. Write an
efficient function for computing G2 from G.
l. Compute and return sum of degrees of all the neighbors of each vertex. Let Nsum[v] be the sum of
degrees(out degrees) of all the neighbors of a vertex v in an undirected(directed) graph G(V, E).
Devise an O(|V|+|E|) function to compute the value of Nsum for each vertex in G.
m. Develop a function Is2Colorable that returns true if an undirected graph is 2-colorable and false
otherwise. An undirected graph G(V, E) is k-colorable if k different colors are enough to color the
vertices of the graph such that no two adjacent vertices share a common color. Below is an example
of 3-colorable graph. Hint: you can use BFS to solve this problem
Do include all the necessary boundary checks in your code. Such as an edge can only be added if a
vertex exists.
Template is not a requirement.