GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/dp/min_cost_path.py at master · deba999/algorithms Expand file tree/ Copy pathmin_cost_path.pyMore file actions 53 lines (37 loc) · 1.29 KB / Copy pathmin_cost_path.pyFile metadata and controls53 lines (37 loc) · 1.29 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 """ author @goswami-rahul To find minimum cost path from station 0 to station N-1, where cost of moving from ith station to jth station is given as: Matrix of size (N x N) where Matrix[i][j] denotes the cost of moving from station i --> station j for i < j NOTE that values where Matrix[i][j] and i > j does not mean anything, and hence represented by -1 or INF For the input below (cost matrix), Minimum cost is obtained as from { 0 --> 1 --> 3} = cost[0][1] + cost[1][3] = 65 the Output will be: The Minimum cost to reach station 4 is 65 Time Complexity: O(n^2) Space Complexity: O(n) """ INF = float("inf") def min_cost(cost): N = len(cost) # dist[i] stores minimum cost from 0 --> i. dist = [INF] * N dist[0] = 0 # cost from 0 --> 0 is zero. for i in range(N): for j in range(i + 1, N): dist[j] = min(dist[j], dist[i] + cost[i][j]) return dist[N - 1] if __name__ == '__main__': cost = [[0, 15, 80, 90], # cost[i][j] is the cost of [-1, 0, 40, 50], # going from i --> j [-1, -1, 0, 70], [-1, -1, -1, 0]] # cost[i][j] = -1 for i > j N = len(cost) mcost = min_cost(cost) assert mcost == 65 print("The Minimum cost to reach station %d is %d" % (N, mcost)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |