Skip to content

Instantly share code, notes, and snippets.

@addy
Created January 9, 2017 15:03
Show Gist options
  • Save addy/3e485fab1bf5ba0d8d96e22fe883450c to your computer and use it in GitHub Desktop.
Save addy/3e485fab1bf5ba0d8d96e22fe883450c to your computer and use it in GitHub Desktop.
public class Solution {
public Map<Character, GraphNode> map = new HashMap<>();
public Set<String> relations = new HashSet<>();
public Set<GraphNode> visited = new HashSet<>();
public Stack<GraphNode> topSort = new Stack<>();
public String alienOrder(String[] words)
{
for (int i = 0; i < words.length - 1; i++)
{
Queue<Character> queue1 = new LinkedList<>();
Queue<Character> queue2 = new LinkedList<>();
for (int j = 0; j < words[i].length(); j++)
{
queue1.add(words[i].charAt(j));
}
for (int j = 0; j < words[i + 1].length(); j++)
{
queue2.add(words[i + 1].charAt(j));
}
while (!queue1.isEmpty() && !queue2.isEmpty())
{
char node1 = queue1.remove();
char node2 = queue2.remove();
if (!map.containsKey(node1))
{
map.put(node1, new GraphNode(node1));
}
if (!map.containsKey(node2))
{
map.put(node2, new GraphNode(node2));
}
if (node1 == node2) continue;
if (!relations.contains("" + node1 + node2))
{
relations.add("" + node1 + node2);
map.get(node1).addNeighbor(map.get(node2));
}
}
while (!queue1.isEmpty())
{
char node1 = queue1.remove();
if (!map.containsKey(node1))
{
map.put(node1, new GraphNode(node1));
}
}
while (!queue2.isEmpty())
{
char node1 = queue2.remove();
if (!map.containsKey(node1))
{
map.put(node1, new GraphNode(node1));
}
}
}
if (relations.size() == 0) return "";
topologicalSort();
StringBuilder sb = new StringBuilder();
while (!topSort.isEmpty())
{
sb.append(topSort.pop().val);
}
return sb.toString();
}
public void topologicalSort()
{
for (GraphNode node : map.values())
{
if (!visited.contains(node))
{
dfs(node);
}
}
}
public void dfs(GraphNode root)
{
if (root == null) return;
visited.add(root);
for (GraphNode node : root.neighbors)
{
if (!visited.contains(node)) dfs(node);
}
topSort.push(root);
}
}
class GraphNode {
public char val;
public List<GraphNode> neighbors;
public GraphNode(char val) {
this.val = val;
neighbors = new ArrayList<>();
}
public void addNeighbor(GraphNode node)
{
neighbors.add(node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment