图的遍历

  • 神马是图

    简单来说,图就是由一些小圆点(称为顶点)和连接这些小圆点的直线(称为边)组成。

    这里写图片描述

    对于一个图,我们最常见的需要就是遍历一个图,通过这些边到达每一个顶点。通常我们有两种方式去遍历所有的顶点,一种是深度优先遍历,另一种是广度优先遍历。(对于深度与广度可以参考之前的文章)。

  • 图的表示方法

    在计算机语言中我们通常可以通过一个二维数组表示一个图。如同下图:

    这里写图片描述

    图中的1表示有边可以联通两个顶点,∞表示没有边联通,0表是自己到自己。这种存储图的方式称为图的邻接矩阵存储法。

  • 图的深度优先遍历

    public static Scanner scanner;
    public static int chart[][]=new int[5][5];
    public static boolean book[][]=new boolean[5][5];
    public static int sum=0;
    public static void dfs(int step){
        sum++;
        if(sum==chart.length){
            return;
        }            //当遍历完成后结束遍历
        System.out.print(step+"\t");
        for(int i=0;i<chart.length;i++ ){
            if(chart[step][i]==1&&book[step][i]==false){
                book[step][i]=true;
                dfs(i);
            }
        }
    }
    //初始化数据
    @Before
    public void init(){
        scanner=new Scanner(System.in);
        for(int i=0;i<chart.length;i++){
            for(int j=0;j<chart[i].length;j++){
                if(i==j){
                    chart[i][j]=0;
                }
                else{
                    chart[i][j]=Integer.MAX_VALUE;
                }
            }
        }
        for(int i=0;i<5;i++){
            int x=scanner.nextInt();
            int y=scanner.nextInt();
            chart[x][y]=1;
        }
    }
    
    @Test
    public void testDfs(){
        dfs(0);
    }
  • 图的广度优先遍历

    public static Scanner scanner;
    public static int chart[][]=new int[5][5];
    public static boolean book[][]=new boolean[5][5];
    public static int sum=0;
    
    public void bfs(){
        Queue<Integer> queue=new LinkedList<Integer>();
        queue.offer(0);
        while(!queue.isEmpty()){
            int head=queue.poll();
            sum++;
            System.out.println(head);
            if(sum==chart.length){
                return;
            }
    
            for(int i=0;i<chart.length;i++){
                if(chart[head][i]==1&&book[head][i]==false){
                    book[head][i]=true;
                    queue.offer(i);
                }
            }
        }
    }
    
    @Before
    public void init(){
        scanner=new Scanner(System.in);
        for(int i=0;i<chart.length;i++){
            for(int j=0;j<chart[i].length;j++){
                if(i==j){
                    chart[i][j]=0;
                }
                else{
                    chart[i][j]=Integer.MAX_VALUE;
                }
            }
        }
        for(int i=0;i<5;i++){
            int x=scanner.nextInt();
            int y=scanner.nextInt();
            chart[x][y]=1;
        }
    }
    @Test
    public void testDfs(){
        bfs();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值