Java实现广度、深度优先搜索遍历

public class test1 {
    //深度优先搜索
    public static void dfsByMatrix(char[] c, int[][] matrix, int n, int[] visit) {
        System.out.println(c[n]);
        visit[n] = 1;//已经遍历过
        for(int j = 0; j < matrix[n].length; j ++){
            if(matrix[n][j] == 1 && visit[j] == 0){
                dfsByMatrix(c,matrix,j,visit);
            }
        }
    }
    //获得字符所在位置
    public static int getPosition(char[] c, char s){
        int i;
        for( i = 0; i< c.length; i ++){
            if(c[i] == s){
                return i;
            }
        }
        return -1;
    }
    //广度优先搜索遍历
    public static void bfsByMatrix(int[][]matrix, int[] vistited, char[] c, int n, Queue sq){
       sq.add(c[n]);
       while(! sq.empty()){
           char s = sq.peek();
           n = getPosition(c,s);
           if(vistited[n] == 0) {
               System.out.println(s);
           }
           vistited[n] = 1;
           sq.poll();
           for(int i =0; i < matrix[n].length; i ++){
               if(matrix[n][i] == 1 && vistited[i] ==0){
                   sq.add(c[i]);
               }
           }
       }
    }

    public static void main(String[] args) {
        char[] c = {'B', 'C', 'A', 'E', 'F', 'G', 'D'};
        int[][] matrix = {{0, 1, 0, 0, 0, 0, 0}, {1, 0, 1, 0, 0, 0, 1}, {0, 1, 0, 0, 1, 0, 1,}, {0, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 0}, {0, 1, 1, 0, 0, 0, 0}};
        int n = getPosition(c,'A');
        int[] visit = new int[c.length];
        dfsByMatrix(c,matrix,n,visit);
        Queue sq = new Queue(2*c.length);
        bfsByMatrix(matrix,visit,c,n,sq);
    }
}

public class Queue {
    int front;
    int rear;
    int maxsize;
    char[] c ;
    public Queue(int maxsize){
        this.maxsize = maxsize;
        c = new char[maxsize];
        front = rear = 0;
    }
    public boolean empty(){
        return front == rear ? true : false;
    }
    public boolean add(char a){
        if(rear <= maxsize) {
            c[rear++] = a;
            return true;
        }
        return false;
    }
    public char peek(){
       return c[front];
    }
    public void poll(){
        front++;
    }
    public int getFront(){
        return front;
    }
    public void setFront(int front){
        this.front = front;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43408956/article/details/89488974