min Path Algorithm

The Min Path Algorithm, also known as the Shortest Path Algorithm or Dijkstra's Algorithm, is a widely-used graph search procedure that finds the shortest path between two nodes in a weighted graph. This algorithm was conceived by computer scientist Edsger W. Dijkstra in 1956 and is particularly useful in various applications such as network routing, transportation planning, and artificial intelligence. The main idea behind the algorithm is to iteratively explore the nodes in the graph, maintaining a set of unvisited nodes and their corresponding minimum distances from the starting node. By always visiting the node with the smallest known distance, the algorithm ensures that the shortest path is found efficiently. The algorithm begins by initializing the distance of the starting node to zero and all other nodes to infinity. It then repeatedly selects the unvisited node with the smallest known distance and updates the distances of its neighbors. This process is repeated until either the target node is visited or all nodes have been processed. To keep track of the path, a predecessor for each node is stored, which can be used to reconstruct the shortest path once the algorithm is completed. The Min Path Algorithm is guaranteed to find the shortest path in graphs with non-negative edge weights and can be optimized using priority queues to achieve better time complexity.
/**
 * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
 *
 * Note: You can only move either down or right at any point in time.
 *
 * Can we do it in O(1) space complexity?
 */

#include <iostream>
#include <vector>
#include <utility>

int minPathSum(std::vector<std::vector<int>>& grid) {
	size_t m = grid.size();
	size_t n = grid[0].size();
	for ( size_t i = 1; i < m; ++i ) {
		grid[i][0] += grid[i-1][0];
	}
	for ( size_t i = 1; i < n; ++i ) {
		grid[0][i] += grid[0][i-1];
	}

	for ( size_t i = 1; i < m; ++i ) {
		for ( size_t j = 1; j < n; ++j ) {
			grid[i][j] += std::min( grid[i-1][j], grid[i][j-1]);
		}
	}
	return grid[m-1][n-1];
}

int main() {
	std::vector<std::vector<int>> grid {
									{ 1, 0, 5 },
									{ 2, 3, 1},
									{ 4, 1, 9}
								  };
	for ( size_t i = 0; i < grid.size(); ++i ) {
		for ( size_t j = 0; j < grid[0].size(); ++j ) {
			std::cout << grid[i][j] << " ";
		}
		std::cout << std::endl;
	}
	std::cout << "Min cost for above grid from moving top left to bottom right is "
			  <<  minPathSum(grid) << std::endl;
	return 0;
}

LANGUAGE:

DARK MODE: