Created
July 14, 2014 00:39
-
-
Save jyhjuzi/11fb399098dafe34a3b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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