图的邻接表存储

来源:互联网 发布:linux 下ide 编辑:程序博客网 时间:2024/04/29 07:30

邻接表是图的一种链式存储结构。在邻接表中,对图中每个顶点建立一个单链表,第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 0
原创粉丝点击