1.将题目给定的图转化为自己经常使用的图结构 例如:题目给定一个二维数组,二维数组的每一行第一个数表示边的权值,第二个值和第三个值表示两个节点,由第二个值代表的节点指向第三个值代表的节点
public static Graph CreateGraph(int[][] matrix){
//graph二维数组每一行第一个表示边的权重weight,后两个表示两个相连的节点
Graph g = new Graph();
int j = 0;
for (int i = 0; i < matrix.length; i++) {
Node from = new Node(matrix[i][1]);
Node to = new Node(matrix[i][2]);
Edge edge = new Edge(matrix[i][0],from,to);
if(!g.nodes.containsKey(matrix[i][1])){
g.nodes.put(matrix[i][1],from);
}
if(!g.nodes.containsKey(matrix[i][2])){
g.nodes.put(matrix[i][2],to);
}
g.edges.add(edge);
from.out++;
to.in++;
from.nexts.add(to);
from.edges.add(edge);
}
return g;
}
2.给定一个节点,完成图的广度优先遍历
//图的广度优先遍历
public static void BFS(Node node){
if(node==null) return;
Queue<Node> queue = new LinkedList<>();
HashSet<Node> set = new HashSet<>();
queue.add(node);
set.add(node);
while (!queue.isEmpty()){
Node cur = queue.poll();
System.out.println(cur.value);
for (Node next : cur.nexts) {
if(!set.contains(next)){
queue.add(next);
set.add(next);
}
}
}
}
3.给定一个节点完成图的深度优先遍历
//图的深度优先遍历
public static void DFS(Node node){
if (node==null) return;
Stack<Node> stack = new Stack<>();
HashSet<Node> set = new HashSet<>();
stack.push(node);
set.add(node);
System.out.println(node.value);
while (!stack.isEmpty()){
Node cur = stack.pop();
for (Node next : cur.nexts) {
if(!set.contains(next)){
set.add(next);
stack.push(cur);
stack.push(next);
System.out.println(next);
break;
}
}
}
}
4.完成一个图的拓扑排序
//拓扑排序
public static ArrayList<Node> TopoLogy(Graph graph){
if(graph==null) return new ArrayList<>();
//InZeroqueue存放当前入度为0的节点
Queue<Node> InZeroqueue = new LinkedList<>();
//map记录每个节点的入度
HashMap<Node, Integer> map = new HashMap<>();
ArrayList<Node> res = new ArrayList<>();
Collection<Node> nodes = graph.nodes.values();
for (Node node : nodes) {
map.put(node,node.in);
if(node.in==0){
InZeroqueue.add(node);
}
}
//当InZeroqueue不为空,循环弹出节点并擦除他发散出去的边
while (!InZeroqueue.isEmpty()){
Node cur = InZeroqueue.poll();
res.add(cur);
for (Node next : cur.nexts) {
map.put(next,map.get(next)-1);
if(map.get(next)==0){
InZeroqueue.add(next);
}
}
}
return res;
}