一、图的相关结构
1、点结构
import java. util. ArrayList ;
public class Node {
public int value;
public int in;
public int out;
public ArrayList < Node > nexts;
public ArrayList < Edge > edges;
public Node ( int value) {
this . value = value;
in = 0 ;
out = 0 ;
nexts = new ArrayList < > ( ) ;
edges = new ArrayList < > ( ) ;
}
}
2、边结构
public class Edge {
public int weight;
public Node from;
public Node to ;
public Edge ( int weight, Node from, Node to ) {
this . weight = weight;
this . from = from;
this . to = to ;
}
}
3、图结构
import java. util. HashMap ;
import java. util. HashSet ;
public class Graph {
public HashMap < Integer , Node > nodes;
public HashSet < Edge > edges;
public Graph ( ) {
nodes = new HashMap < > ( ) ;
edges = new HashSet < > ( ) ;
}
}
二、BFS以及DFS
1、BFS
import java. util. HashSet ;
import java. util. LinkedList ;
import java. util. Queue ;
public class Code01_BFS {
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) ) {
set. add ( next) ;
queue. add ( next) ;
}
}
}
}
}
2、DFS
import java. util. HashSet ;
import java. util. Stack ;
public class Code02_DFS {
public static void dfs ( Node node) {
if ( node == null ) {
return ;
}
Stack < Node > stack = new Stack < > ( ) ;
HashSet < Node > set = new HashSet < > ( ) ;
stack. add ( node) ;
set. add ( node) ;
System . out. println ( node. value) ;
while ( ! stack. isEmpty ( ) ) {
Node cur = stack. pop ( ) ;
for ( Node next : cur. nexts) {
stack. push ( cur) ;
stack. push ( next) ;
set. add ( next) ;
System . out. println ( next. value) ;
break ;
}
}
}
}
三、拓扑排序
import java. util. * ;
public class Code03_TopologySort {
public static List < Node > sortedTopology ( Graph graph) {
HashMap < Node , Integer > inMap = new HashMap < > ( ) ;
Queue < Node > zeroInQueue = new LinkedList < > ( ) ;
for ( Node node : graph. nodes. values ( ) ) {
inMap. put ( node, node. in) ;
if ( node. in == 0 ) {
zeroInQueue. add ( node) ;
}
}
List < Node > result = new ArrayList < > ( ) ;
while ( ! zeroInQueue. isEmpty ( ) ) {
Node cur = zeroInQueue. poll ( ) ;
result. add ( cur) ;
for ( Node next : cur. nexts) {
inMap. put ( next, inMap. get ( next) - 1 ) ;
if ( inMap. get ( next) == 0 ) {
zeroInQueue. add ( next) ;
}
}
}
return result;
}
}