图的邻接表存储

邻接表是图的一种链式存储结构。在邻接表中,对图中每个顶点建立一个单链表,第i个单链表中的节点表示依附于顶点Vi的边。


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Node{
    String point; //顶点
    int value; //权值
    Node next;
}

public class Graph {
    
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int temp;
        Node node;
        Node p;
        Node[] nodes=new Node[n];
        boolean[] visited=new boolean[n];
        for(int i=0;i<n;i++){
            nodes[i]=new Node();
            nodes[i].point=i+"";
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                temp=scanner.nextInt();
                if(temp!=0){
                    node=new Node();
                    node.point=j+"";
                    node.value=temp;
                    p=nodes[i];
                    while(p.next!=null){
                        p=p.next;
                    }
                    p.next=node;
                }
            }
        }
        
        DFS(nodes,visited,0);
        System.out.println();
        
        for(int i=0;i<n;i++)
            visited[i]=false;
        
        BFS(nodes,visited);
    }
    
//    深度优先遍历从某个顶点出发,首先访问这个顶点,然后找出刚访问这个
//    结点的第一个未被访问的邻结点,然后再以此邻结点为顶点,继续找它的
//    下一个新的顶点进行访问,重复此步骤,直到所有结点都被访问完为止。
    
    //深度优先搜索
    public static void DFS(Node[] nodes,boolean[] visited,int i){
        if(visited[i]==true){ //若该点已访问过
            return;
        }
        System.out.print(nodes[i].point);
        visited[i]=true;
        Node temp=nodes[i].next;
        int point;
        while(temp!=null){   //递归处理该点的连接点
            point=Integer.parseInt(temp.point);
            DFS(nodes,visited,point);
            temp=temp.next;
        }
    }

//    广度优先遍历从某个顶点出发,首先访问这个顶点,然后找出这个结点的
//    所有未被访问的邻接点,访问完后再访问这些结点中第一个邻接点的所有
//    结点,重复此方法,直到所有结点都被访问完为止。
    public static void BFS(Node[] nodes,boolean[] visited){
        Queue<Node> queue=new LinkedList<Node>();
        queue.add(nodes[0]);
        Node temp;
        int point;
        while(!queue.isEmpty()){
            temp=queue.poll();
            point=Integer.parseInt(temp.point);
            if(!visited[point]){
               System.out.print(temp.point);
               visited[point]=true;
               temp=temp.next;
               while(temp!=null){
                   point=Integer.parseInt(temp.point);
                   if(!visited[point]){ //若该点已被访问过,则不加入队列
                       queue.add(nodes[point]);//将该点的连接点加入队列
                   }
                   temp=temp.next;
               }
            }
        }
    }
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值