Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Last active February 2, 2020 20:42
Show Gist options
  • Save andriybuday/46cb36371b82e8e848b94951c18c37b5 to your computer and use it in GitHub Desktop.
Save andriybuday/46cb36371b82e8e848b94951c18c37b5 to your computer and use it in GitHub Desktop.
Breadth First Search
boolean[] visited = new boolean[n];
Deque<Integer> queue = new LinkedList();
queue.offer(0);
while(!queue.isEmpty()) {
int x = queue.poll();
// 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]) {
queue.offer(y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment