Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Created July 14, 2014 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyhjuzi/11fb399098dafe34a3b4 to your computer and use it in GitHub Desktop.
Save jyhjuzi/11fb399098dafe34a3b4 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class Q4_2 {
public static void main(String[] args) {
NodeWithState nodea = new NodeWithState("a");
NodeWithState nodeb = new NodeWithState("b");
NodeWithState nodec = new NodeWithState("c");
NodeWithState noded = new NodeWithState("d");
nodea.nexts.add(nodeb);
nodec.nexts.add(nodeb);
noded.nexts.add(nodea);
System.out.println(isConnected(nodea,noded));
}
static boolean isConnected(NodeWithState source, NodeWithState des) {
if(source == des)
return true;
Queue<NodeWithState> q = new LinkedList<NodeWithState>();
q.add(source);
source.state = State.VISITING;
while (!q.isEmpty()) {
NodeWithState current = q.poll();
if (current.nexts != null && current.nexts.size() != 0) {
for (NodeWithState node : current.nexts) {
if (des == node)
return true;
else if (node.state == State.UNVISITED) {
node.state = State.VISITING;
q.add(node);
}
}
}
current.state = State.VISITED;
}
return false;
}
}
enum State {
VISITED, VISITING, UNVISITED;
}
class NodeWithState {
String value;
ArrayList<NodeWithState> nexts;
State state;
NodeWithState(String val) {
value = val;
nexts = new ArrayList<NodeWithState>();
state = State.UNVISITED;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment