Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active August 12, 2022 12:42
Show Gist options
  • Save nattybear/d6241c06c8722c3e7409d700e1becb34 to your computer and use it in GitHub Desktop.
Save nattybear/d6241c06c8722c3e7409d700e1becb34 to your computer and use it in GitHub Desktop.
import java.util.*;
class ListOfInteger extends ArrayList<Integer> {}
class Graph extends HashMap<Integer,ListOfInteger> {}
public class Main {
static List discovered = new ListOfInteger();
static List explored = new ListOfInteger();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int m = sc.nextInt();
Graph graph = new Graph();
for (int i = 1; i <= n; i++)
graph.put(i, new ListOfInteger());
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
graph.get(a).add(b);
graph.get(b).add(a);
}
bfs(graph, 1, 3);
System.out.println(explored);
}
static void dfs(Graph g, int v) {
discovered.add(v);
g.get(v).forEach(w -> {
if (!discovered.contains(w))
dfs(g, w);
});
}
static int bfs(Graph g, int root, int goal) {
List queue = new ListOfInteger();
explored.add(root);
queue.add(root);
while (!queue.isEmpty()) {
System.out.println(queue);
int v = (int)queue.remove(0);
if (v == goal) {
System.out.println("gotcha!");
return v;
}
g.get(v).forEach(w -> {
if (!explored.contains(w)) {
explored.add(w);
queue.add(w);
}
});
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment