http://articles.leetcode.com/2012/05/clone-graph-part-i.html
BFS方法遍历图。为了防止重复遍历,使用hashmap,key为原图的node,value为新图的node。
我没有看原文的算法实现先是自己想了然后写上去。这样的过程中我碰到了一些问题。比如说什么时候创建新的节点?是在while的开始,还是在遍历相邻节点的时候?这点很重要。
实现:
package com.song.algorithm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Image {
public static class Node {
public int data;
public List<Node> neighbors;
}
public Node head;
public static Image copy(Image image) {
Queue<Node> queue = new LinkedList<Node>();
if (image.head == null) {
return null;
}
Image cp = new Image();
HashMap<Node, Node> map = new HashMap<Node, Node>();
Node newHead = new Node();
newHead.data = image.head.data;
cp.head = newHead;
map.put(image.head, newHead);
queue.add(image.head);
while (!queue.isEmpty()) {
Node node = queue.remove();
Node cnode = map.get(node);
if (node.neighbors != null) {
List<Node> cnodeNeighbors = new ArrayList<Node>();
cnode.neighbors = cnodeNeighbors;
for (Node n : node.neighbors) {
if (map.get(n) == null) {
Node newNode = new Node();
newNode.data = n.data;
map.put(n, newNode);
cnodeNeighbors.add(newNode);
queue.add(n);
} else {
cnodeNeighbors.add(map.get(n));
}
}
}
}
return cp;
}
public static void iterate(Image image) {
HashSet<Node> set = new HashSet<Node>();
set.add(image.head);
Queue<Node> queue = new LinkedList<Node>();
queue.add(image.head);
while (!queue.isEmpty()) {
Node node = queue.remove();
System.out.print(node.data + " ");
if (node.neighbors != null) {
for (Node n : node.neighbors) {
if (!set.contains(n)) {
queue.add(n);
set.add(n);
}
}
}
}
}
public static void main(String[] args) {
Image image = new Image();
Node head = new Node();
image.head = head;
head.data = 1;
ArrayList<Node> nei1 = new ArrayList<Node>();
Node n2 = new Node();
n2.data = 2;
nei1.add(n2);
head.neighbors = nei1;
ArrayList<Node> nei2 = new ArrayList<Node>();
Node n3 = new Node();
n3.data = 3;
nei2.add(n3);
Node n4 = new Node();
n4.data = 4;
nei2.add(n4);
n2.neighbors = nei2;
ArrayList<Node> nei3 = new ArrayList<Node>();
nei3.add(head);
n4.neighbors = nei3;
iterate(image);
System.out.println("");
Image image1 = copy(image);
iterate(image1);
}
}