Given a graph represented by an adjacency list and a vertex, write a program to remove the given vertex and all edges connected to that vertex.
Input Format:
The graph is represented as an adjacency list: a dictionary or list where adj[i] contains all nodes adjacent to node i.
For example, adj = {0: [1,2], 1: [0,2], 2: [0,1,3], 3: [2]} or adj = [[1,2],[0,2],[0,1,3],[2]] represents a graph with 4 nodes (0 to 3), where node 0 is connected to nodes 1 and 2, node 1 to 0 and 2, etc.
The vertex to remove is given as an integer vertex (0-based index).
graph LR
subgraph I["Input"]
A(0) --- B(1)
A --- C(2):::red
B --- C
C --- D(3)
end
subgraph O["Output"]
A2(0) --- B2(1)
D2(3)
end
I ~~~ O
classDef red fill:#FF0000,stroke:#000,stroke-width:1px,color:#fff;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Input:
adj ={0:[1,2],1:[0,2],2:[0,1,3],3:[2]}vertex =2Output:
{0:[1],1:[0],3:[]}Explanation: Vertex 2 and all its edges are removed from the graph.
classSolution {
publicvoidremoveVertex(Map<Integer, List<Integer>> adj, int v) {
for (List<Integer> nbrs : adj.values()) {
nbrs.removeIf(x -> x == v);
}
adj.remove(v);
}
}
1
2
3
4
5
6
classSolution:
defremove_vertex(self, adj: dict[int, list[int]], v: int) ->None:
for nbrs in adj.values():
if v in nbrs:
nbrs[:] = [x for x in nbrs if x != v]
adj.pop(v, None)