Last active
June 11, 2026 18:58
-
-
Save thinkphp/166374bd57eb2e00824b0f39de3b22b4 to your computer and use it in GitHub Desktop.
Breadth First Search - 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.io.*; | |
| import java.util.*; | |
| class GraphAdjMatrix { | |
| private int[][] mat; | |
| private boolean[] vizitat; | |
| private int n; | |
| public GraphAdjMatrix(int n) { | |
| this.n = n; | |
| this.mat = new int[n][n]; | |
| this.vizitat = new boolean[n]; | |
| } | |
| public void citeste(Scanner sc) { | |
| 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(); | |
| } | |
| } | |
| } | |
| //foloseste structura de data COADA | |
| //in timp ce DFS foloseste STACK | |
| // 0 | |
| public void BFS(int start) { | |
| Queue<Integer> coada = new LinkedList<>(); | |
| vizitat[ start ] = true; | |
| coada.add( start ); | |
| while(!coada.isEmpty()) { | |
| int nod = coada.poll(); | |
| System.out.print(nod + " ");//0 | |
| for(int vecin = 0; vecin < n; vecin++) { //>>1 2 | |
| if(mat[nod][vecin] == 1 && !vizitat[vecin]) { | |
| vizitat[ vecin ] = true; | |
| coada.add( vecin ); | |
| } | |
| } | |
| } | |
| } | |
| public boolean esteVizitat(int i) { | |
| return vizitat[ i ]; | |
| } | |
| public int getN() { | |
| return n; | |
| } | |
| } | |
| public class Main { | |
| public static void main(String[] args) throws Exception{ | |
| Scanner sc = new Scanner(new File("graph.in")); | |
| System.out.println("Numarul de noduri: "); | |
| int n = sc.nextInt(); | |
| GraphAdjMatrix g = new GraphAdjMatrix( 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