2642. 设计可以求最短路径的图类

2642. 设计可以求最短路径的图类


题目链接:2642. 设计可以求最短路径的图类

代码如下:

class Graph 
{
public:
    Graph(int n, vector<vector<int>>& edges) 
    {
        this->n=n;
        this->graph=vector<vector<int>>(n,vector<int>(n,max));
        for(const auto& edge:edges)
        {
            int x=edge[0];
            int y=edge[1];
            int cost=edge[2];
            graph[x][y]=cost;
        }
    }
    
    void addEdge(vector<int> edge) 
    {
        graph[edge[0]][edge[1]]=edge[2];
    }
    
    //迪杰斯特拉
    int shortestPath(int node1, int node2) 
    {
        vector<bool> visited(n,false);
        vector<int> dist(n,max);
        dist[node1]=0;
        for(int i=0;i<n;i++)
        {
            int t=-1;
            for(int j=0;j<n;j++)
            {
                if(!visited[j]&&(t==-1||dist[t]>dist[j]))
                    t=j;
            }
            visited[t]=true;
            for(int j=0;j<n;j++)
                dist[j]=min(dist[j],dist[t]+graph[t][j]);
        }
        return dist[node2]>=max?-1:dist[node2];
    }
private:
    vector<vector<int>> graph;
    int n;
    const int max=1<<29;
};

/**
 * Your Graph object will be instantiated and called as such:
 * Graph* obj = new Graph(n, edges);
 * obj->addEdge(edge);
 * int param_2 = obj->shortestPath(node1,node2);
 */

相关推荐

  1. 2642. 设计可以路径

    2024-04-05 06:18:02       38 阅读
  2. 论——路径

    2024-04-05 06:18:02       42 阅读
  3. folyd算法路径

    2024-04-05 06:18:02       43 阅读
  4. 【刷路径算法

    2024-04-05 06:18:02       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-05 06:18:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-05 06:18:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-05 06:18:02       87 阅读
  4. Python语言-面向对象

    2024-04-05 06:18:02       96 阅读

热门阅读

  1. Linux文件权限管理详解——以CentOS为例

    2024-04-05 06:18:02       33 阅读
  2. Github 2024-04-04 Go开源项目日报 Top10

    2024-04-05 06:18:02       31 阅读
  3. 2024年最新社交相亲系统源码下载

    2024-04-05 06:18:02       32 阅读
  4. Python数据分析与可视化笔记 九 分类问题

    2024-04-05 06:18:02       43 阅读
  5. Spring Boot 集成 RabbitMQ(一)

    2024-04-05 06:18:02       37 阅读
  6. Day2-Hive的多字段分区,分桶和数据类型

    2024-04-05 06:18:02       39 阅读
  7. 自动化分享----pywinauto

    2024-04-05 06:18:02       39 阅读
  8. ansible安装

    2024-04-05 06:18:02       37 阅读
  9. 每日一题 --- 滑动窗口最大值[力扣][Go]

    2024-04-05 06:18:02       38 阅读