Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class GraphSearch {
- public static void main(String[] args){
- int[][] graph = {{1,1,0,1,0},{0,0,0,0,1},{1,1,1,0,0},{1,1,1,1,0},{0,0,0,0,0}};
- /*
- for (int i=0;i<3;i++)
- for (int j=0;j<3;j++)
- System.out.println(graph[i][j]);
- */
- //depth(graph,3);
- breadth(graph,0);
- }
- public static void depth(int[][] graph, int root){
- // x is where it's going
- // y is how you get there
- for (int i=0;i<graph.length;i++)
- graph[i][root] = 0; // set the return values to 0
- System.out.println(root);
- for (int i=0;i<graph.length;i++){
- if (graph[root][i]==1)
- depth(graph,i);
- }
- }
- // =======================================================
- public static void breadth(int[][] graph, int root)
- {
- Queue<Integer> q = new LinkedList<Integer>();
- for (int i=0;i<graph.length;i++)
- graph[i][root] = 0; // set the return values to 0
- q.add(root);
- System.out.println(root);
- while(!q.isEmpty()){
- root = q.remove();
- for (int i=0;i<graph.length;i++) {
- if (graph[root][i]==1){
- System.out.println(i);
- for (int j=0;j<graph.length;j++)
- graph[j][i] = 0; // set the return values to 0
- q.add(i);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement