21xrx.com
2024-11-22 06:34:52 Friday
登录
文章检索 我的文章 写文章
Dijkstra算法的C++代码
2023-07-09 14:14:19 深夜i     --     --
Dijkstra算法 C++ 代码

Dijkstra算法是解决最短路径问题的一种经典算法。它可以解决从某个起点到目标节点的最短路径问题,通常在图论问题中经常被使用。下面是Dijkstra算法的C++代码示例。

首先,定义一个结构体来表示每一个节点,包括节点的编号、是否被访问过以及当前已知的最短距离。


struct Node {

  int id;

  bool visited;

  int dist;

  Node(int id)

    this->id = id;

    visited = false;

    dist = INT_MAX;

  

};

接下来,定义一个函数来实现Dijkstra算法。输入参数是节点的数量、起点、终点以及节点之间的距离矩阵。该函数使用一个vector来存储所有的节点,并将起点的dist设置为0。


void dijkstra(int n, int src, int dst, vector<vector<int>> &graph) {

  vector<Node> nodes;

  for (int i = 0; i < n; i++) {

    nodes.push_back(Node(i));

  }

  nodes[src].dist = 0;

  // Main loop

  while (true) {

    // Find the unvisited node with the smallest distance

    int minDist = INT_MAX;

    Node* currNode = NULL;

    for (auto &node : nodes) {

      if (node.visited || node.dist == INT_MAX)

        continue;

      

      if (node.dist < minDist)

        minDist = node.dist;

        currNode = &node;

      

    }

    if (currNode == NULL)

      break;

    

    currNode->visited = true;

    // Update the distances of contiguous nodes

    for (int j = 0; j < n; j++) {

      if (graph[currNode->id][j] == 0)

        continue;

      

      int newDist = currNode->dist + graph[currNode->id][j];

      if (newDist < nodes[j].dist) {

        nodes[j].dist = newDist;

      }

    }

  }

  // Print the shortest path from src to dst

  if (nodes[dst].dist == INT_MAX)

    cout << "No path found";

    return;

  

  vector<int> path;

  int curr = dst;

  while (curr != src) {

    path.push_back(curr);

    for (int i = 0; i < n; i++) {

      if (graph[i][curr] != 0 && nodes[curr].dist == nodes[i].dist + graph[i][curr])

        curr = i;

        break;

      

    }

  }

  path.push_back(src);

  reverse(path.begin(), path.end());

  cout << "Shortest path: ";

  for (auto &node : path)

    cout << node << " ";

  

  cout << endl << "Distance: " << nodes[dst].dist << endl;

}

最后,我们可以定义一个包含几个节点和边的示例图,并运行dijkstra函数来查找起点到终点的最短路径。


int main() {

  int n = 6;

  vector<vector<int>> graph(n, vector<int>(n, 0));

  graph[0][1] = 2;

  graph[0][2] = 5;

  graph[0][3] = 3;

  graph[1][3] = 1;

  graph[1][4] = 4;

  graph[2][3] = 2;

  graph[2][5] = 6;

  graph[3][4] = 3;

  graph[3][5] = 7;

  graph[4][5] = 1;

  dijkstra(n, 0, 5, graph);

  return 0;

}

运行结果将输出最短路径以及距离:


Shortest path: 0 1 3 4 5

Distance: 10

以上就是Dijkstra算法的C++代码示例,我们希望这篇文章能够对您有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复