Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created May 17, 2026 15:22
Show Gist options
  • Select an option

  • Save thinkphp/4c09f81cf6b84f0456961e1fd504c5d1 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/4c09f81cf6b84f0456961e1fd504c5d1 to your computer and use it in GitHub Desktop.
Graf/Citire/DFS
import java.util.*;
public class Graf {
private final int[][] mat;
public final boolean[] vizitat;
private final int n;
public Graf(int n) {
this.n = n;
this.mat = new int[n][n];
this.vizitat = new boolean[n];
}
public void citeste() {
Scanner sc = new Scanner(System.in);
System.out.println("Introduceti matricea de adiacenta");
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
mat[i][j] = sc.nextInt();
}
}
}
public void DFS(int nod) {
vizitat[nod] = true;
System.out.print((nod + 1) + " ");
for(int vecin = 0; vecin < n; ++vecin) {
if(mat[nod][vecin] == 1 && !vizitat[vecin]) {
DFS( vecin );
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Numarul de noduri: ");
int n = sc.nextInt();
Graf g = new Graf( n );
g.citeste();
System.out.println("Parcurgere DFS: ");
for(int i = 0; i < n; ++i) {
if(!g.vizitat[i]) {
g.DFS(i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment