#K94417. Matrix Target Sum Sequence
Matrix Target Sum Sequence
Matrix Target Sum Sequence
You are given a square matrix with dimensions \(n \times n\) containing integer values and a target integer \(T\). Your task is to determine if there exists a sequence of cells in the matrix such that the sum of their values exactly equals \(T\). The sequence can start at any cell and you may move in any of the eight possible directions (up, down, left, right, and the four diagonals). However, you cannot revisit the same cell in a single sequence.
Note: The sequence can be of any length as long as the moving rule is followed and the sum of the selected numbers equals \(T\). If such a sequence exists, output YES
; otherwise, output NO
.
inputFormat
The input is read from stdin
in the following format:
n T row1_element1 row1_element2 ... row1_elementn row2_element1 row2_element2 ... row2_elementn ... rown_element1 rown_element2 ... rown_elementn
Here, the first line contains two integers: \(n\) (the dimension of the square matrix) and \(T\) (the target sum). The next \(n\) lines each contain \(n\) space-separated integers representing the matrix.
outputFormat
The output is a single line printed to stdout
containing either YES
if a valid sequence exists or NO
if it does not.
3 8
1 2 3
4 5 6
7 8 9
YES