Created
June 11, 2026 19:03
-
-
Save thinkphp/bba4ca0ba450cf83a3fccb9fb5f1f843 to your computer and use it in GitHub Desktop.
DFS cu matricea de adiacenta
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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