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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值