Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created June 11, 2026 19:23
Show Gist options
  • Select an option

  • Save thinkphp/8aaf4efbabbe6a72d83b0d9dac437b67 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/8aaf4efbabbe6a72d83b0d9dac437b67 to your computer and use it in GitHub Desktop.
BFS cu Adj Lists
import java.io.*;
import java.util.*;
class GraphAdjLinkedList {
private static class Node {
int vecin;
Node urmator;
Node(int vecin) {
this.vecin = vecin;
this.urmator = null;
}
}
private Node[] cap; //vector de liste de adiacenta
private boolean[] vizitat;
private int n;
public GraphAdjLinkedList(int n) {
this.n = n;
this.cap = new Node[n];
this.vizitat = new boolean[n];
}
public void addEdge(int u, int v) {
Node nou = new Node(v);
nou.urmator = cap[u];
cap[u] = nou;
}
public void citeste(Scanner sc) {
System.out.print("Numarul de muchii: ");
int m = sc.nextInt();
System.out.print("Introduceti muchiile: ");
for(int i = 0; i < m; ++i) {
int u = sc.nextInt();
int v = sc.nextInt();
System.out.println(u + " -- " + v);
u--;
v--;
addEdge(u, v);
addEdge(v, u);
}
}
public void BFS(int start) {
Queue<Integer> coada = new LinkedList<>();
coada.add(start);
vizitat[start] = true;
while(!coada.isEmpty()) {
int node = coada.poll();
System.out.print((node + 1) + " ");
for(Node p = cap[node]; p != null; p = p.urmator) {
if(!vizitat[p.vecin]) {
vizitat[p.vecin] = true;
coada.add(p.vecin);
}
}
}
}
public boolean esteVizitat(int i) {
return vizitat[i];
}
}
public class MainLinkedList {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("graph2.in"));
System.out.println("Numarul de noduri: ");
int n = sc.nextInt();
GraphAdjLinkedList g = new GraphAdjLinkedList( n );
g.citeste( sc );
System.out.println("Parcurgere BFS: ");
for(int i = 0; i < n; ++i) {
if(!g.esteVizitat(i)) {
g.BFS( i );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment