一、 深度优先搜索
List<Integer> visited = new ArrayList<>();
public void dfs(Node node) {
if (node == null) {
return;
}
if (visited.contains(node.val)) {
return;
}
System.out.print(node.val + "->");
visited.add(node.val);
for (int i = 0; i < node.neighbors.size(); i++) {
dfs(node.neighbors.get(i));
}
}
二、 广度优先搜索
List<Integer> visited = new ArrayList<>();
public void bfs(Node node) {
if (node == null) {
return;
}
LinkedList<Node> queue = new LinkedList<>();
queue.add(node);
visited.add(node.val);
while (!queue.isEmpty()) {
Node n = queue.poll();
System.out.println(n.val + "->");
for (Node neighbor: n.neighbors) {
if (!visited.contains(neighbor.val)) {
visited.add(neighbor.val);
queue.add(neighbor);
}
}
}
}