Add Prims Algorithm using Greedy Technique to find Minimum Cost Spanning Trees #6069
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This Java code implements Prim's Algorithm to find the Minimum Spanning Tree (MST) of a given weighted graph represented by a cost matrix. It reads the cost matrix and number of vertices from user input, then calculates and displays the minimum cost edges that form the MST along with the total minimum cost.
The algorithm uses a greedy approach, beginning from an initial vertex and progressively adding the shortest edge that connects a new vertex to the growing MST. The pr function performs the core operations, updating the minimum cost and the list of nearest vertices.
Test Case:
Input:
Number of vertices: 4
Cost matrix:
0 2 0 6
2 0 3 8
0 3 0 0
6 8 0 0
Output
Enter the number of vertices:
4
Enter the cost matrix:
Min Tree edges are
1: Minimum edge is <1, 2> Cost: 2
2: Minimum edge is <2, 3> Cost: 3
3: Minimum edge is <1, 4> Cost: 6
Minimum cost: 11
clang-format -i --style=file path/to/your/file.java