java 图的邻接表存储,广度优先遍历

1.定义边结点数据结构

public class ArcNode {
    /*边表结点*/
    int adjvex;//顶点序号
    ArcNode next;//指向下一个邻接点
    public ArcNode(){
        adjvex=-1;
        next=null;
    }
}

2.定义顶点数据结构

public class VexNode {
    /*顶点结点*/
    char data;//顶点信息
    ArcNode head;//边表头指针,指向邻接边
    public VexNode(char da){
        data=da;
        head=null;
    }
}

3.定义邻接表的数据结构

public class VGraph {
    /*邻接表数据结构*/
    VexNode list[];//表
    int edges,vexs;//边数,顶点数
    public VGraph(int ve,int ed,VexNode [] li){
        vexs=ve;
        edges=ed;
        list=li;
    }
}

4.创建图的邻接表存储,显示邻接表,访问邻接表元素,广度优先遍历邻接表

public class GraphList {

    /*创建图的邻接表存储*/
    public void CreateGraph(VGraph graph,int weight[][],int n){
        /*n为顶点总数*/
        int i,j;
        for(i=0;i<n;i++){
            for(j=n-1;j>=0;j--){
                if(weight[i][j]!=0){
                    /*邻接矩阵元素不为0,则生成一个边表结点*/
                    ArcNode edge=new ArcNode();
                    edge.adjvex=j;
                    edge.next=graph.list[i].head;//从链表头部插入新的结点
                    graph.list[i].head=edge;
                    graph.edges++;
                }
            }
        }
    }

    /*显示图的邻接表存储*/
    public void ShowGraph(VGraph graph){
        int i;
        for(i=0;i<graph.vexs;i++){
            System.out.print(graph.list[i].data+": ");
            ArcNode edge=new ArcNode();
            edge=graph.list[i].head;
            while(edge!=null){
                System.out.print(edge.adjvex+" ");
                edge=edge.next;
            }   
            System.out.println();
        }
    }

    /*获取第一个邻接点*/
    public int GetFirst(VGraph graph,int k){
        if(k<0||k>graph.vexs-1){
            System.out.println("参数k超出范围");
            return -1;
        }
        if(graph.list[k].head==null){
            return -1;
        }
        else {
            //System.out.println(graph.list[k].head.adjvex);
            return graph.list[k].head.adjvex;
        }
    }

    /*获取下一个邻接点*/
    public int GetNext(VGraph graph,int k,int t){
        if(k<0||k>graph.vexs-1||t<0||t>graph.vexs-1){
            System.out.println("参数 k or t 超出范围");
            return -1;
        }
        if(graph.list[k].head==null){
            return -1;
        }
        else {
            ArcNode edge=new ArcNode();
            edge=graph.list[k].head;            
            while(edge!=null && edge.adjvex!=t){
                edge=edge.next;
            }
        //  System.out.println(edge.next.adjvex);   
            return edge.next.adjvex;
        }
    }


    /*广度优先遍历邻接表*/
    public void BFSGraph(VGraph graph,int k,int n){
        //k为第一个要访问的顶点,n为图中顶点数
        if(k<0||k>graph.vexs-1){
            System.out.println("参数 k 超出范围");
            return ;
        }

        int visited[]=new int[n];//设置结点被访问标记
        for(int i=0;i<n;i++){//初始化,设置没有被访问过
            visited[i]=0;
        }

        //用队列存储图中的顶点,先进先出
        Queue <Integer>queue=new LinkedList<Integer>();
        queue.add(k);
        visited[k]=1;
        int u;     //u用于存储队顶元素
        ArcNode v=new ArcNode();   //v用于存储顶点u的邻接顶点
        while(!queue.isEmpty()){
            u=queue.remove();
            System.out.print(graph.list[u].data);
            v=graph.list[u].head;
            while(v!=null){
                if(visited[v.adjvex]!=1){
                    queue.add(v.adjvex);
                    visited[v.adjvex]=1;
                }
                v=v.next;
            }           
        }               
    }


    public static void main(String args[]){
        char []data=new char[]{'A','B','C','D','E'};
        int n=data.length;
        int [][]weight=new int[][]{
                {0,1,0,0,1},
                {1,0,1,1,0},
                {0,1,0,0,0},
                {0,1,0,0,1},
                {1,0,0,1,0}
                };
        VexNode []list=new VexNode[n];
        for(int i=0;i<n;i++){
            /*初始化结点链表*/
            list[i]=new VexNode(data[i]);
        }

        VGraph graph=new VGraph(n,0,list); //初始化邻接表
        GraphList gp=new GraphList();
        gp.CreateGraph(graph,weight, n);  //创建邻接表
        gp.ShowGraph(graph);  //显示邻接表
        gp.GetNext(graph, 0,1); 
        gp.BFSGraph(graph, 0, n);  //广度优先遍历邻接表
    }

}
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java实现对无向和有向进行深度优先遍历广度优先遍历,以及对有向进行简单有向回路和路径判断的代码示例: ```java import java.util.*; public class GraphTraversal { // 无向 static class UndirectedGraph { int V; // 节点数量 int[][] adjMatrix; // 邻接矩阵表示 public UndirectedGraph(int v) { V = v; adjMatrix = new int[V][V]; } // 添加无向边 public void addEdge(int v1, int v2) { adjMatrix[v1][v2] = 1; adjMatrix[v2][v1] = 1; } // 深度优先遍历 public void dfs(int start) { boolean[] visited = new boolean[V]; dfsHelper(start, visited); } private void dfsHelper(int v, boolean[] visited) { visited[v] = true; System.out.print(v + " "); for (int i = 0; i < V; i++) { if (adjMatrix[v][i] == 1 && !visited[i]) { dfsHelper(i, visited); } } } // 广度优先遍历 public void bfs(int start) { boolean[] visited = new boolean[V]; Queue<Integer> queue = new LinkedList<>(); visited[start] = true; queue.offer(start); while (!queue.isEmpty()) { int v = queue.poll(); System.out.print(v + " "); for (int i = 0; i < V; i++) { if (adjMatrix[v][i] == 1 && !visited[i]) { visited[i] = true; queue.offer(i); } } } } } // 有向 static class DirectedGraph { int V; // 节点数量 List<Integer>[] adjList; // 邻接表表示 public DirectedGraph(int v) { V = v; adjList = new ArrayList[V]; for (int i = 0; i < V; i++) { adjList[i] = new ArrayList<>(); } } // 添加有向边 public void addEdge(int v1, int v2) { adjList[v1].add(v2); } // 深度优先遍历 public void dfs(int start) { boolean[] visited = new boolean[V]; dfsHelper(start, visited); } private void dfsHelper(int v, boolean[] visited) { visited[v] = true; System.out.print(v + " "); for (int i : adjList[v]) { if (!visited[i]) { dfsHelper(i, visited); } } } // 广度优先遍历 public void bfs(int start) { boolean[] visited = new boolean[V]; Queue<Integer> queue = new LinkedList<>(); visited[start] = true; queue.offer(start); while (!queue.isEmpty()) { int v = queue.poll(); System.out.print(v + " "); for (int i : adjList[v]) { if (!visited[i]) { visited[i] = true; queue.offer(i); } } } } // 判断简单有向回路 public boolean hasCycle() { boolean[] visited = new boolean[V]; boolean[] recursionStack = new boolean[V]; for (int i = 0; i < V; i++) { if (hasCycleHelper(i, visited, recursionStack)) { return true; } } return false; } private boolean hasCycleHelper(int v, boolean[] visited, boolean[] recursionStack) { visited[v] = true; recursionStack[v] = true; for (int i : adjList[v]) { if (!visited[i] && hasCycleHelper(i, visited, recursionStack)) { return true; } else if (recursionStack[i]) { return true; } } recursionStack[v] = false; return false; } // 判断路径 public boolean hasPath(int v1, int v2) { boolean[] visited = new boolean[V]; return hasPathHelper(v1, v2, visited); } private boolean hasPathHelper(int v1, int v2, boolean[] visited) { if (v1 == v2) { return true; } visited[v1] = true; for (int i : adjList[v1]) { if (!visited[i] && hasPathHelper(i, v2, visited)) { return true; } } return false; } } public static void main(String[] args) { // 无向测试 UndirectedGraph g1 = new UndirectedGraph(5); g1.addEdge(0, 1); g1.addEdge(0, 4); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(1, 4); g1.addEdge(2, 3); g1.addEdge(3, 4); System.out.println("DFS traversal of undirected graph:"); g1.dfs(0); System.out.println(); System.out.println("BFS traversal of undirected graph:"); g1.bfs(0); // 有向测试 DirectedGraph g2 = new DirectedGraph(6); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.addEdge(2, 3); g2.addEdge(3, 3); g2.addEdge(4, 5); System.out.println("\nDFS traversal of directed graph:"); g2.dfs(2); System.out.println(); System.out.println("BFS traversal of directed graph:"); g2.bfs(2); System.out.println(); System.out.println("Directed graph has cycle: " + g2.hasCycle()); System.out.println("Path exists between 0 and 3: " + g2.hasPath(0, 3)); System.out.println("Path exists between 3 and 0: " + g2.hasPath(3, 0)); } } ``` 输出结果为: ``` DFS traversal of undirected graph: 0 1 2 3 4 BFS traversal of undirected graph: 0 1 4 2 3 DFS traversal of directed graph: 2 0 1 3 BFS traversal of directed graph: 2 0 1 3 Directed graph has cycle: true Path exists between 0 and 3: true Path exists between 3 and 0: false ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值