Problem
Basics
Graph
In computer science, a graph is defined as a set of vertices paired with a set of edges. The vertices are represented by circles, and the edges are the lines between them. Edges connect a vertex to other vertices.
The following are also graphs:
Tree and linked list
On the left is a tree structure, on the right a linked list. They can be considered graphs but in a simpler form. They both have
vertices (nodes) and edges (links).
The first graph includes cycles, where you can start off at a vertex, follow a path, and come back to the original vertex. A tree is a graph without such cycles.
Another common type of graph is the directed acyclic graph or DAG:
DAG
Like a tree, this graph does not have any cycles (no matter where you start, there is no path back to the starting vertex), but this graph has directional edges with the shape that does not necessarily form a hierarchy.
Adjacency list
The adjacency list describes outgoing edges. A has an edge to B, but B does not have an edge back to A, so A does not appear in B’s adjacency list. Finding an edge or weight between two vertices can be expensive because there is no random access to edges. You must traverse the adjacency lists until it is found.
Adjacency Matrix.
In an adjacency matrix implementation, a matrix with rows and columns representing vertices stores a weight to indicate if vertices are connected and by what weight.
Analysis Process
1.HashMap is used to store all the visited nodes and the key of the clone node HashMap to store the nodes of the original graph. Value stores the corresponding nodes in the clone diagram to prevent them from falling into a dead loop, and to obtain the nodes of the clone graph
2.Add the first node to the queue clone add the first node to the HashMap named Visited
3.BFS
Fetch a node from the head of the queue
Traverses all of the nodes’ adjacencies
If an adjacent point has been visited, the adjacent point must be in visited, then the adjacent point is obtained from visited
Otherwise, create a new node to store in visited
Adds the cloned adjacency point to the adjacency list of the corresponding node in the clone diagram
Code
golang
/**
* Definition for a Node.
* type Node struct {
* Val int
* Neighbors []*Node
* }
*/
func cloneGraph(node *Node) *Node {
if node == nil {
return node
}
// use bfs algorithm to traverse the graph and get all nodes.
nodes := getNodes(node)
// copy nodes, store the old->new mapping information in a hash map
mapping := make(map[*Node]*Node)
for _, n := range nodes {
mapping[n] = &Node{Val: n.Val}
}
// copy neighbors(edges)
for _, n := range nodes {
newNode := mapping[n]
for _, neighbor := range n.Neighbors {
newNeighbor := mapping[neighbor]
newNode.Neighbors = append(newNode.Neighbors, newNeighbor)
}
}
return mapping[node]
}
func getNodes(node *Node) []*Node {
var queue []*Node
set := make(map[*Node]bool)
queue = append(queue, node)
set[node] = true
for len(queue) > 0 {
head := queue[0]
queue = queue[1:]
for _, neighbor := range head.Neighbors {
if _, ok := set[neighbor]; !ok {
set[neighbor] = true
queue = append(queue, neighbor)
}
}
}
var res []*Node
for k := range set {
res = append(res, k)
}
return res
}
java
class Solution {
public Node cloneGraph(Node node) {
if(node == null) return null;
Map<Node, List<Node>> graph = new HashMap<>();//use map to store figure
List<Node> v = new ArrayList<>();//bfs
v.add(node);
graph.put(node, node.neighbors);
while(!v.isEmpty()){
Node p = v.get(0);
v.remove(0);
for(Node i : p.neighbors){
if(!graph.containsKey(i)){
v.add(i);
graph.put(i, i.neighbors);
}
}
}
List<Node> vec = new ArrayList<>(graph.keySet());//Gets all nodes of the old diagram
int k = vec.indexOf(node);
List<Node> r = new ArrayList<>();//Copy the new image using the subscript of the old one
for(int i = 0; i < vec.size(); ++i) r.add(new Node(vec.get(i).val));
for(int i = 0; i < vec.size(); ++i){
for(int j = 0; j < vec.get(i).neighbors.size(); ++j){
r.get(i).neighbors.add(r.get(vec.indexOf(vec.get(i).neighbors.get(j))));
}
}
return r.get(k);
}
}