Route Between Two Nodes in Graph(図中の2点間の路線)
1478 ワード
http://www.lintcode.com/en/problem/route-between-two-nodes-in-graph/?rand=true
解析はClone Graph(クローン図)を参照してください。
解析はClone Graph(クローン図)を参照してください。
/**
* Definition for Directed graph.
* class DirectedGraphNode {
* int label;
* ArrayList neighbors;
* DirectedGraphNode(int x) {
* label = x;
* neighbors = new ArrayList();
* }
* };
*/
public class Solution {
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
public boolean hasRoute(ArrayList graph,
DirectedGraphNode s, DirectedGraphNode t) {
// write your code here
if (s == t) {
return true;
}
// list 。
ArrayList visited = new ArrayList<>();
visited.add(s);
for (int i = 0; i < visited.size(); i++) {
DirectedGraphNode node = visited.get(i);
for (DirectedGraphNode temp : node.neighbors) {
if (temp == t) {
return true;
}
if (visited.contains(temp)) {
continue;
}
visited.add(temp);
}
}
return false;
}
}