Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Created February 2, 2020 20:47
Show Gist options
  • Save andriybuday/c0ae30b5ef026a6d7b11d9b9582c77c0 to your computer and use it in GitHub Desktop.
Save andriybuday/c0ae30b5ef026a6d7b11d9b9582c77c0 to your computer and use it in GitHub Desktop.
Depth First Search
boolean[] visited = new boolean[n];
Deque<Integer> stack = new LinkedList();
stack.push(0);
while(!stack.isEmpty()) {
int x = stack.pop();
// do something to generate the output of your algorithm
// or just return x if that's what you are searching for
visited[x] = true;
int[] nextElements = getElementsAssessibleFromX(x);
for(int y: nextElements) {
if(!visited[y]) {
stack.push(y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment