Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added multistage-graph in dynamic programming #853

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
INF = 99

def shortestDist(graph, n, source, target):
dist = [INF] * (n + 1)
path = [-1] * (n + 1)

dist[target] = 0
path[target] = target

for i in range(target - 1, 0, -1):
for j in range(i + 1, n + 1):
if graph[i][j] != INF and dist[i] > graph[i][j] + dist[j]:
dist[i] = graph[i][j] + dist[j]
path[i] = j

if dist[source] == INF:
print(f"There is no path from node {source} to node {target}")
return

print(f"The shortest path distance from node {source} to node {target} is: {dist[source]}")

print("Path:", source, end="")
current = source
while current != target:
current = path[current]
print(f" -> {current}", end="")
print()

def main():
n = int(input("Enter the number of vertices in the graph: "))

graph = [[INF] * (n + 1) for _ in range(n + 1)]

print(f"Enter the adjacency matrix (use {INF} for INF):")
for i in range(1, n + 1):
row = list(map(int, input(f"Row {i}: ").split()))
for j in range(1, n + 1):
graph[i][j] = row[j - 1]

source = int(input("Enter the source node: "))
target = int(input("Enter the target node: "))

shortestDist(graph, n, source, target)

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
* Medium-Dp-Problems
* [Coin-Change](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/coin-change.py)
* [Longest-Inc-Subseq](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/longest-inc-subseq.py)
* [Multistage-Graph](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/multistage-graph.py)
* [Partition-Subset-Sum](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/partition-subset-sum.py)
* [Unique-Paths](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/unique-paths.py)
* Heapsort
Expand Down