分别用邻接矩阵和邻接表实现图的深度优先遍历和广度优先遍历_图论-图的构建...

上一篇文章,对于图有了一个简单的描述,对于图的存储一般有两种方式:邻接表和邻接矩阵,这篇文章分别用C++和Java实现图的构建

61b5e18a18b1797245eccc4543edb89b.png

图论-图的构建

相关文章

图论-图的构建

深度优先搜索遍历图

广度优先搜索遍历图

实现代码(C++)

  main.cpp//  Graph  Created by 陈龙//  Copyright © 2019 陈龙. All rights reserved.//#include #include using namespace std;//最大顶点数const int maxV = 1000;//邻接矩阵,二维数组实现int G[maxV][maxV];//边int edge = 0;//创建图void createGraph(int x,int y,bool isDirection){    if (G[x][y]==1) {        return;    }    G[x][y]=1;    edge++;    if (!isDirection) {        G[y][x]=1;    }}//某个节点的出度int outEdge(int x){    int num = 0;    for (int i=0; i adj[maxV];int edgeForTable = 0;void createGraphForTable(int x,int y,int w,bool isDirection){    adj[x].push_back(Node(y,w));    if (!isDirection) {        adj[y].push_back(Node(x,w));    }    edgeForTable++;}int main(int argc, const char * argv[]) {    //初始化邻接矩阵    int isDirection = false;    createGraph(1,3,isDirection);    createGraph(2,3,isDirection);    createGraph(2,4,isDirection);    createGraph(2,5,isDirection);    cout<实现代码(Java)
public class Graph {    private static List> lists = new ArrayList<>();    public static void main(String[] args) {        Graph graph = new Graph();        for (int i = 0; i < 10; i++) {            lists.add(new ArrayList<>());        }        graph.createGraphForTable(1, 3, 2);        graph.createGraphForTable(2, 3, 3);        graph.createGraphForTable(2, 4, 3);        graph.createGraphForTable(2, 5, 3);        System.out.println("顶点2的度为=" + lists.get(2).size());        System.out.println("顶点1的度为=" + lists.get(1).size());    }    private List> createGraphForTable(int u, int v, int w) {        Node node = new Node(v, w);        if (!lists.get(u).isEmpty()) {            for (Node nodeTemp : lists.get(u)) {                if (nodeTemp.v == v) {                    //替换                    nodeTemp.w = w;                    return lists;                }            }        }        lists.get(u).add(node);        return lists;    }    static class Node {        int v;        int w;        public Node(int v, int w) {            this.v = v;            this.w = w;        }    }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值