{"id":23872992,"url":"https://github.com/yusufss4/graph-algorithms","last_synced_at":"2026-06-18T22:32:05.387Z","repository":{"id":270124475,"uuid":"909344435","full_name":"Yusufss4/graph-algorithms","owner":"Yusufss4","description":"This repository contains a single Java implementation of two classic graph algorithms: Bellman-Ford for shortest path calculation in directed graphs (supporting negative edge weights) and Prim’s Algorithm for constructing Minimum Spanning Trees in undirected graphs.","archived":false,"fork":false,"pushed_at":"2024-12-28T16:12:45.000Z","size":7,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-22T20:13:51.916Z","etag":null,"topics":["bellman-ford-algorithm","data-structures-and-algorithms","graphs","prims-algorithm"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Yusufss4.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","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":"2024-12-28T12:26:27.000Z","updated_at":"2024-12-28T16:12:48.000Z","dependencies_parsed_at":"2024-12-28T16:32:32.537Z","dependency_job_id":"5157129e-d4d2-4a95-b34c-55ffe47f9f7d","html_url":"https://github.com/Yusufss4/graph-algorithms","commit_stats":null,"previous_names":["yusufss4/graph-algorithms"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Yusufss4/graph-algorithms","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yusufss4%2Fgraph-algorithms","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yusufss4%2Fgraph-algorithms/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yusufss4%2Fgraph-algorithms/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yusufss4%2Fgraph-algorithms/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Yusufss4","download_url":"https://codeload.github.com/Yusufss4/graph-algorithms/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yusufss4%2Fgraph-algorithms/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34510283,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-18T02:00:06.871Z","response_time":128,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["bellman-ford-algorithm","data-structures-and-algorithms","graphs","prims-algorithm"],"created_at":"2025-01-03T16:37:44.068Z","updated_at":"2026-06-18T22:32:05.371Z","avatar_url":"https://github.com/Yusufss4.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"## README\n\n### Overview\n\nThis repository contains a **single Java file** (`CompactMain.java`) that implements two classic graph algorithms:\n\n1. **Bellman-Ford** – Finds the shortest paths from a single source to all other vertices in a **directed** graph, allowing for **negative edge weights**.\n2. **Prim’s** – Constructs a **Minimum Spanning Tree (MST)** of an **undirected** graph starting from a specified source vertex.\n\nThis project is written for the Boğaziçi University Master of Science in Software Engineering SWE 510.01 Data Structures and Algorithms course to showcase the usage of Bellman-Ford and Prim's algorithms on graphs.\n\n---\n\n## Table of Contents\n\n- [README](#readme)\n  - [Overview](#overview)\n- [Table of Contents](#table-of-contents)\n- [How to Compile and Run](#how-to-compile-and-run)\n- [Input Format](#input-format)\n  - [Example: Bellman-Ford](#example-bellman-ford)\n  - [Example: Prim’s](#example-prims)\n- [Classes and Code Structure](#classes-and-code-structure)\n  - [1. `Edge` Class](#1-edge-class)\n  - [2. `Graph` Class](#2-graph-class)\n  - [3. `PrimAlgorithm` Class](#3-primalgorithm-class)\n  - [4. `BellmanFordAlgorithm` Class](#4-bellmanfordalgorithm-class)\n  - [5. `CompactMain` Class](#5-compactmain-class)\n- [Algorithm Descriptions](#algorithm-descriptions)\n  - [Bellman-Ford Algorithm](#bellman-ford-algorithm)\n  - [Prim’s Algorithm](#prims-algorithm)\n\n---\n\n## How to Compile and Run\n\n1. **Clone** or **download** this repository.\n2. **Navigate** to the folder containing `CompactMain.java`.\n3. **Compile**:\n   ```bash\n   javac CompactMain.java\n   ```\n4. **Run**:\n   ```bash\n   java CompactMain\n   ```\n5. **Provide input** in the **formats described** below (manually, or redirect from a file).\n\n---\n\n## Input Format\n\nThe program reads from standard input (e.g., console or a file). The **first line** is the algorithm name (`Bellman-ford` or `Prim’s`).\n\n1. `Bellman-ford` expects **directed** edges separated by the symbol `→`.\n2. `Prim’s` expects **undirected** edges separated by the symbol `-`.\n\nFollow this with a line like `\"12 edges\"` to specify how many edges there are.\n\nThen, provide **that many** lines of edges in the format:\n\n```\nA → B: 4\n```\n\nor\n\n```\nA - B: 4\n```\n\nFinally, end with the source vertex line, e.g.:\n\n```\nsource: A\n```\n\n### Example: Bellman-Ford\n\n```\nBellman-ford\n12 edges\nA → B: 4\nA → C: 2\nB → C: 3\nB → D: 2\nB → E: 3\nC → B: -1\nC → F: 4\nD → F: -3\nD → G: 1\nE → G: -2\nF → H: 2\nG → F: -2\nsource: A\n```\n\n### Example: Prim’s\n\n```\nPrim’s\n11 edges\nA - B: 3\nA - C: 1\nA - D: 5\nB - C: 6\nB - E: 7\nC - D: 2\nC - E: 4\nD - F: 8\nE - F: 9\nE - G: 2\nF - G: 6\nsource: A\n```\n\n---\n\n## Classes and Code Structure\n\nBelow is a **high-level overview** of the classes in `CompactMain.java`.\n\n### 1. `Edge` Class\n\nA lightweight container for a directed edge:\n\n```java\nclass Edge {\n    int source;\n    int destination;\n    int weight;\n    ...\n}\n```\n\n- **`source`**: The integer index of the source vertex\n- **`destination`**: The integer index of the destination vertex\n- **`weight`**: The edge weight (can be negative for Bellman-Ford)\n\n### 2. `Graph` Class\n\nResponsible for:\n\n- **Mapping** vertex labels (e.g. `\"A\"`) to an integer ID (`0, 1, 2, ...`).\n- Holding:\n  - An **adjacency list** (`adjacencyList`) for Prim’s (undirected).\n  - A **list of directed edges** (`directedEdges`) for Bellman-Ford.\n\nKey methods:\n\n- `getOrCreateVertexId(label)`: Assigns an ID to a new label or retrieves an existing one.\n- `addDirectedEdge(u, v, w)`: Adds a directed edge (for Bellman-Ford).\n- `addUndirectedEdge(u, v, w)`: Adds an undirected edge (for Prim’s).\n- `buildReverseMap()`: Builds a reverse lookup from numeric ID back to label for printing results.\n\n### 3. `PrimAlgorithm` Class\n\nImplements **Prim’s MST** logic with static methods:\n\n- **`runPrim(graph, sourceId)`**: Entry point.\n  1. Initializes arrays:\n     - `inMST[]` to track which vertices are already in MST.\n     - `parent[]` to record MST edges.\n     - `key[]` for the minimum edge weight that connects each vertex to the MST.\n  2. Builds MST using a **min-heap** (`PriorityQueue\u003cint[]\u003e`):\n     - Continually extract the vertex with the smallest key.\n     - Update neighbors that could be connected with cheaper edges.\n     - Priority Queue has the weight and vertex index pair `[weight, vertex]`.\n  3. Computes MST total weight and prints results.\n\n### 4. `BellmanFordAlgorithm` Class\n\nImplements **Bellman-Ford** with static methods:\n\n- **`runBellmanFord(graph, sourceId)`**: Entry point.\n  1. Initializes `distance[]` with `Integer.MAX_VALUE`, except `distance[sourceId] = 0`.\n  2. **Relaxes** all edges up to `(V - 1)` times in `relaxEdges()`.\n  3. Checks for **negative-weight cycles** in `containsNegativeWeightCycle()`.\n  4. Prints distances if there is no negative cycle.\n\n### 5. `CompactMain` Class\n\nContains the `main(...)` method. Handles:\n\n1. **Reading** user input with a `Scanner`.\n2. Determining whether to run **Bellman-Ford** or **Prim’s**.\n3. Parsing edge lines and building the `Graph` object.\n4. Reading the **source** vertex.\n5. **Calling** the appropriate algorithm’s `run...()` method.\n\n---\n\n## Algorithm Descriptions\n\n### Bellman-Ford Algorithm\n\n**Purpose**: Finds the shortest path from a single source to all other vertices in a **directed** graph, which **may contain negative edge weights**.\n\n1. **Initialization**:\n   - `distance[source] = 0`; all other `distance[v] = ∞`.\n2. **Edge Relaxation** (repeated `V - 1` times):\n   - For each directed edge `(u, v, w)`, if `distance[u] + w \u003c distance[v]`, update `distance[v] = distance[u] + w`.\n   - This progressively improves estimates of the shortest paths.\n3. **Negative Cycle Detection**:\n   - Perform one more pass. If any `distance[v]` can still be improved, a **negative cycle** exists, and the algorithm stops means that the shortest path can be reduced indefinitely.\n\n### Prim’s Algorithm\n\n**Purpose**: Finds a **Minimum Spanning Tree** (MST) in a weighted **undirected** graph.\n\n1. **Initialization**:\n   - Pick a source vertex (e.g., `A`).\n   - Maintain `key[v]`, which is the **minimum weight** edge connecting `v` to the MST.\n2. **MST Construction**:\n   - Use a **min-heap** to choose the **next** vertex with the **smallest** `key[v]` value.\n   - Mark it as included in MST (`inMST[v] = true`).\n   - Update `key[w]` of the neighbors `w` if the new edge to w is cheaper.\n3. **Repeat** until all vertices are in MST or the min-heap is empty.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyusufss4%2Fgraph-algorithms","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyusufss4%2Fgraph-algorithms","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyusufss4%2Fgraph-algorithms/lists"}