Skip to content

Instantly share code, notes, and snippets.

@dacc
Created March 25, 2012 01:57
Show Gist options
  • Save dacc/2190719 to your computer and use it in GitHub Desktop.
Save dacc/2190719 to your computer and use it in GitHub Desktop.
import java.util.Stack;
/**
*
*/
public class Circuits {
class Position {
int node;
int cost; Position(int node, int cost) { this.node = node; this.cost = cost; }
}
public int howLong(String[] connects, String[] costs) {
int max = 0;
Stack<Position> toVisit = new Stack<Position>();
boolean[] visited = new boolean[connects.length];
int unvisited = connects.length;
while (toVisit.size() > 0 || unvisited > 0) {
if (toVisit.size() < 1) {
int start = 0;
for (; visited[start]; start++);
toVisit.push(new Position(start, 0));
}
Position cursor = toVisit.pop();
if (connects[cursor.node].length() > 0) {
String[] adjacent = connects[cursor.node].split(" ");
String[] adjcosts = costs[cursor.node].split(" ");
for (int i = 0; i < adjacent.length; i++)
toVisit.push(new Position(Integer.parseInt(adjacent[i]),
Integer.parseInt(adjcosts[i]) + cursor.cost));
}
visited[cursor.node] = true;
unvisited--;
if (cursor.cost > max)
max = cursor.cost;
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment