#C4787. Path Sum in Matrix
Path Sum in Matrix
Path Sum in Matrix
You are given a matrix of positive integers with m rows and n columns. Starting from the top-left corner, you can only move either right or down. Your task is to determine whether there exists a path to the bottom-right corner such that the sum of the numbers along the path is exactly equal to a given target value.
The path sum includes the values from both the starting cell and the ending cell.
Input Restrictions: The matrix elements and the target are positive integers.
Example:
Input: 3 3 5 4 2 1 2 1 7 3 4 15</p>Output: True
In the above example, one valid path is 5 → 4 → 2 → 1 → 3, whose sum equals 15. Note that there can be multiple paths, but you only need to decide whether at least one such path exists.
inputFormat
The first line contains two integers m and n representing the number of rows and columns of the matrix.
The next m lines each contain n space-separated integers, representing the matrix elements.
The last line contains an integer target - the sum you need to match with a valid path.
outputFormat
Output a single line with either True
or False
. Print True
if there exists a path from the top-left to the bottom-right corner such that the sum of the elements along the path equals the given target value, and False
otherwise.
3 3
5 4 2
1 2 1
7 3 4
15
True