克隆图

LeetCode每日一题,133. Clone Graph

先看题目描述

大意就是给定一个无向图,让我们克隆这个无向图

算法和思路

这道题实际上就是让我们遍历这个无向图,所以遍历时候要记录已经访问点,我们用一个字典记录

遍历方法有两种,分别是深度优先遍历和广度优先遍历

算法源码

深度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;

public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}

public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}

public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/

class Solution {
HashMap<Node, Node> visited = new HashMap<>();

public Node cloneGraph(Node node) {
if (node == null) return node;
if (visited.containsKey(node)) return visited.get(node);
Node cloneNode = new Node(node.val, new ArrayList<>());
visited.put(node, cloneNode);
for (Node neighbor: node.neighbors) {
cloneNode.neighbors.add(cloneGraph(neighbor));
}
return cloneNode;
}
}

广度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public Node cloneGraph(Node node) {
if (node == null) return null;
Map<Node, Node> lookup = new HashMap<>();
Node clone = new Node(node.val, new ArrayList<>());
lookup.put(node, clone);
Deque<Node> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()) {
Node tmp = queue.poll();
for (Node n : tmp.neighbors) {
if (!lookup.containsKey(n)) {
lookup.put(n, new Node(n.val, new ArrayList<>()));
queue.offer(n);
}
lookup.get(tmp).neighbors.add(lookup.get(n));
}
}
return clone;
}
}