{"id":22513908,"url":"https://github.com/emahtab/dijkstra-algorithm","last_synced_at":"2026-03-19T23:02:51.684Z","repository":{"id":79525438,"uuid":"408681878","full_name":"eMahtab/dijkstra-algorithm","owner":"eMahtab","description":null,"archived":false,"fork":false,"pushed_at":"2024-09-24T16:15:01.000Z","size":1709,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-03T14:07:45.296Z","etag":null,"topics":["dijkstra-algorithm","graph","shortest-path"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-21T04:01:50.000Z","updated_at":"2024-09-24T16:15:04.000Z","dependencies_parsed_at":"2025-02-02T03:35:34.646Z","dependency_job_id":null,"html_url":"https://github.com/eMahtab/dijkstra-algorithm","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/eMahtab/dijkstra-algorithm","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fdijkstra-algorithm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fdijkstra-algorithm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fdijkstra-algorithm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fdijkstra-algorithm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/dijkstra-algorithm/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fdijkstra-algorithm/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29174046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-06T19:28:14.811Z","status":"ssl_error","status_checked_at":"2026-02-06T19:28:13.420Z","response_time":59,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dijkstra-algorithm","graph","shortest-path"],"created_at":"2024-12-07T03:15:00.015Z","updated_at":"2026-02-06T19:30:55.926Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Dijkstra Algorithm\n\nSingle Source Shortest Path in a graph with non-negative weights using a Priority Queue (Min Heap)\n\n## ❗❗❗ Remember Dijkstra's algorithm doesn't work with negative weights.\n\n## Algorithm :\n1. Take a `distances[]` array and fill it with `Integer.MAX_VALUE` , set `distances[startingVertex] = 0`\n2. Take a `PriorityQueue pq` and pass the comparator to return the minimum weight vertex, `add the startingVertex with weight 0 to pq`\n3. While pq is not empty remove the vertex from the priority queue, if `this vertex is not already visited then visit this vertex and try to relax its neighboring vertices`, if possible.\n4. To relax a neighboring vertex (check if `dU + dUV \u003c dV`), if thats the case add the neighboring vertex v to pq with weight `dU + dUV` and update the distances[v] accordingly.\n5. At the end `distances` array will have **shortest path** to all the vertices from the `startingVertex`\n\n\n# Implementation :\n```java\nimport java.util.*;\n\npublic class App {\n\n\tpublic static void main(String[] args) {\n\t\tint numberOfVertices = 6;\n\t\tint[][] edges = {\n\t\t\t    {0, 1, 7},\n\t\t\t    {0, 3, 5},\n\t\t\t    {3, 2, 3},\n\t\t\t    {1, 4, 8},\n\t\t\t    {2, 4, 4},\n\t\t\t    {4, 5, 5}\n\t\t\t    \n\t\t\t};\n\t\tint startingVertex = 0;\n\t\tfindShortestPath(numberOfVertices, edges, startingVertex);\n\n\t}\n\t\n\tpublic static void findShortestPath(int n, int[][] edges, int src) {\n\t\t// Build the adjacency matrix.\n\t\tint adjMatrix[][] = new int[n][n];\n\t\tfor (int[] edge: edges) {\n\t\t    adjMatrix[edge[0]][edge[1]] = edge[2];\n\t\t}\n\n\t\t// Shortest distances array\n\t\tint[] distances = new int[n];\n\t\tArrays.fill(distances, Integer.MAX_VALUE);\n\t\tdistances[src] = 0; // distance of source vertex from source vertex will be zero\n\n\n\t\t// The priority queue would contain (vertex, cost)\n\t\tPriorityQueue\u003cint[]\u003e minHeap = new PriorityQueue\u003cint[]\u003e((a, b) -\u003e a[1] - b[1]);\n\t\tminHeap.offer(new int[]{src, 0});\n        \n\t\twhile (!minHeap.isEmpty()) { \n\t\t   int[] node = minHeap.poll();\n\t\t   int vertex = node[0];\n\t\t   int distance = node[1];\n\t\t   // Examine and relax all neighboring vertices if possible \n\t\t   for (int v = 0; v \u003c n; v++) {\n\t\t      if (adjMatrix[vertex][v] \u003e 0) {\n\t\t\t  int dU = distance, dUV = adjMatrix[vertex][v], dV = distances[v];\n\t\t\t  // Better path?\n\t\t\t  if (dU + dUV \u003c dV) {\n\t\t\t     minHeap.offer(new int[]{v, dU + dUV});\n\t\t\t     distances[v] = dU + dUV;\n\t\t\t  }\n\t\t       }\n\t\t    }\n\t\t }\n\t\t for(int v = 0; v \u003c n; v++) {\n           \t      System.out.println(\"Shortest path from vertex : V\" + src + \n     \t\t\t\t\" to vertex V\" + v +\" with distance \" + distances[v]); \n        \t }\n         }\n\n}\n\n```\n\n![Shortest Path - Dijkstra Algorithm](graph-1.jpg?raw=true \"Shortest Path\")\n\n### Code execution Output\n```\nShortest path from vertex : V0 to vertex V0 with distance 0\nShortest path from vertex : V0 to vertex V1 with distance 7\nShortest path from vertex : V0 to vertex V2 with distance 8\nShortest path from vertex : V0 to vertex V3 with distance 5\nShortest path from vertex : V0 to vertex V4 with distance 12\nShortest path from vertex : V0 to vertex V5 with distance 17\n```\n\n## Example 2 :\n\n![Shortest Path - Dijkstra Algorithm](graph-2.jpg?raw=true \"Shortest Path\")\n\n```java\npublic static void main(String[] args) {\n\t\tint numberOfVertices = 5;\n\t\tint[][] edges = {\n\t\t\t\t{0,1,10},\n\t\t\t\t{0,4,3},\n\t\t\t\t{4,1,1},\n\t\t\t\t{1,4,4},\n\t\t\t\t{1,2,2},\n\t\t\t\t{4,2,8},\n\t\t\t\t{4,3,2},\n\t\t\t\t{3,2,7},\n\t\t\t\t{2,3,9}\n\t\t\t\t};\n\t\tint startingVertex = 0;\n\t\tfindShortestPath(numberOfVertices, edges, startingVertex);\n}\n```\n\n### Code execution Output\n```\nShortest path from vertex : V0 to vertex V0 with distance 0\nShortest path from vertex : V0 to vertex V1 with distance 4\nShortest path from vertex : V0 to vertex V2 with distance 6\nShortest path from vertex : V0 to vertex V3 with distance 5\nShortest path from vertex : V0 to vertex V4 with distance 3\n```\n\n## Improvement : Using visited boolean array\nWe don't want to visit an already visited vertex again, beacuse the weights are non-negative, so it will not result in shortest weights path.\nSo it doesn't make sense, to try to visit an already visited vertex from a different path.\n```java\npublic static void findShortestPath(int n, int[][] edges, int src) {\n\tboolean[] visited = new boolean[n];\n        // Build the adjacency matrix\n        int adjMatrix[][] = new int[n][n];\n        for (int[] edge: edges) {\n            adjMatrix[edge[0]][edge[1]] = edge[2];\n        }\n        \n        // Shortest distances array\n        int[] distances = new int[n];\n        Arrays.fill(distances, Integer.MAX_VALUE);\n        distances[src] = 0;\n        \n        \n        // The priority queue would contain (vertex, cost)\n        PriorityQueue\u003cint[]\u003e minHeap = new PriorityQueue\u003cint[]\u003e((a, b) -\u003e a[1] - b[1]);\n        minHeap.offer(new int[]{src, 0});\n        \n         while (!minHeap.isEmpty()) { \n            int[] node = minHeap.poll();\n            int vertex = node[0];\n            if(visited[vertex])\n            \tcontinue;\n            visited[vertex] = true;\n            int distance = node[1];\n            // Examine and relax all neighboring vertices if possible \n            for (int v = 0; v \u003c n; v++) {\n                if (adjMatrix[vertex][v] \u003e 0) {\n                    int dU = distance, dUV = adjMatrix[vertex][v], dV = distances[v];\n                    // Better path?\n                    if (dU + dUV \u003c dV) {\n                        minHeap.offer(new int[]{v, dU + dUV});\n                        distances[v] = dU + dUV;\n                    }\n                }\n            }\n         }\n         for(int v = 0; v \u003c n; v++) {\n           System.out.println(\"Shortest path from vertex : V\" + src + \n     \t\t\" to vertex V\" + v +\" with distance \" + distances[v]); \n         }\n    }\n\n```\n\n## References :\n1. https://www.youtube.com/watch?v=sD0lLYlGCJE (Very good explanation)\n\n## Problems :\nhttps://leetcode.com/problems/network-delay-time\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fdijkstra-algorithm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fdijkstra-algorithm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fdijkstra-algorithm/lists"}