1. Linear Scan (Matrix / Array-based Dijkstra)
Intuition
In each of V rounds, scan all vertices to find the unvisited node with minimum distance, then relax all its outgoing edges.
Algorithm
- Create dist array of size V initialized to INF, set dist[src] = 0.
- Create visited boolean array initialized to false.
- Repeat V times:
- Find unvisited vertex u with minimum dist[u].
- Mark visited[u] = true.
- For every neighbor v of u: relax dist[v] = min(dist[v], dist[u] + weight).
- Return dist array.
#include <iostream>#include <vector>#include <algorithm> using namespace std; const int INF = 1e9; vector<int> dijkstraLinear(int V, const vector<vector<pair<int, int>>>& adj, int src) { vector<int> dist(V, INF); vector<bool> visited(V, false); dist[src] = 0; for (int i = 0; i < V; ++i) { int u = -1; for (int j = 0; j < V; ++j) { if (!visited[j] && (u == -1 || dist[j] < dist[u])) { u = j; } } if (dist[u] == INF) break; visited[u] = true; for (const auto& edge : adj[u]) { int v = edge.first, w = edge.second; if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; } } } return dist;} int main() { int V = 3; vector<vector<pair<int, int>>> adj(V); adj[2].push_back({1, 3}); adj[1].push_back({2, 3}); adj[2].push_back({0, 6}); adj[0].push_back({2, 6}); adj[1].push_back({0, 1}); adj[0].push_back({1, 1}); auto res = dijkstraLinear(V, adj, 2); cout << "Linear Scan Dijkstra: "; for (int d : res) cout << d << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V^2) - Space complexity:
O(V)