原文:
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
译文:
给定一个有向图,设计算法判断两结点间是否存在路径。
思路:
如果BFS就用队列
如果DFS就用递归回溯,参考回溯模板:http://blog.csdn.net/fightforyourdream/article/details/16997793
package Tree_Graph;
import java.util.LinkedList;
public class S4_2 {
// ======================== State
enum State{
unvisited, visited, visiting;
}
// ======================== Node
static class Node {
private String vertex;
private Node[] adjacent;
public int adjacentCount;
public State state;
public Node(String vertex, int adjacentLength) {
this.vertex = vertex;
adjacentCount = 0;
adjacent = new Node[adjacentLength];
}
public void addAdjacent(Node x) {
if (adjacentCount < 30) {
this.adjacent[adjacentCount++] = x;
} else {
System.out.println("No more adjacent can be added");
}
}
public Node[] getAdjacent() {
return adjacent;
}
public String getVertex() {
return vertex;
}
}
// ======================== Graph
static class Graph {
private Node[] vertices;
public int count;
public Graph() {
vertices = new Node[6];
count = 0;
}
public void addNode(Node x) {
if (count < 30) {
vertices[count] = x;
count++;
} else {
System.out.println("Graph full");
}
}
public Node[] getNodes() {
return vertices;
}
}
// ============================== BFS
public static boolean bfs(Graph g, Node start, Node end) {
LinkedList<Node> queue = new LinkedList<Node>();
start.state = State.visiting;
queue.add(start);
while ( !queue.isEmpty() ) {
Node cur = queue.remove();
if (cur != null) {
for (Node nbr : cur.getAdjacent()) {
if (nbr.state == State.unvisited) {
if (nbr == end) {
return true;
} else {
nbr.state = State.visiting;
queue.add(nbr);
}
}
}
cur.state = State.visited;
}
}
return false;
}
// ================================= DFS
public static boolean dfs(Graph g, Node start, Node end) {
if ( start == end ) {
return true;
}
for (Node nbr : start.getAdjacent()) {
if (nbr.state == State.unvisited) {
start.state = State.visiting;
if(dfs(g, nbr, end)) {
return true;
}
start.state = State.unvisited;
}
}
return false;
}
public static Graph createNewGraph()
{
Graph g = new Graph();
Node[] temp = new Node[6];
temp[0] = new Node("a", 3);
temp[1] = new Node("b", 0);
temp[2] = new Node("c", 0);
temp[3] = new Node("d", 1);
temp[4] = new Node("e", 1);
temp[5] = new Node("f", 1);
temp[0].addAdjacent(temp[1]);
temp[0].addAdjacent(temp[2]);
temp[0].addAdjacent(temp[3]);
temp[3].addAdjacent(temp[4]);
temp[4].addAdjacent(temp[5]);
temp[5].addAdjacent(temp[0]); // 添加一条边变成环
for (int i = 0; i < 6; i++) {
g.addNode(temp[i]);
}
resetState(g);
return g;
}
public static void resetState(Graph g) {
for (Node u : g.getNodes()) {
u.state = State.unvisited;
}
}
public static void main(String a[])
{
Graph g = createNewGraph();
Node[] n = g.getNodes();
Node start = n[4];
Node end = n[3];
resetState(g);
System.out.println(bfs(g, start, end));
resetState(g);
System.out.println(dfs(g, start, end));
}
}