Sum of Traversed Integers in a 2D Array
You are given a two dimensional array containing arrays of integers as an argument. Starting at the top left of the 2D array, move either up, down, left, or right to the greatest neighboring integer. When an integer has been visited, set its value to zero. Stop traversing the array when all neighboring integers are zero and return the sum of all visited integers.
The inner arrays will always be equal in length.
Requirements
- Must return a single integer
Example #1
solve([
[5, 7, 4, 3],
[1, 3, 8, 9],
[8, 3, 6, 1],
[7, 3, 5, 2]
])
> 36
- We start out at the top left element 5 and set it to zero.
- The next largest integer between 7 and 1 is 7, so we move to the right and set it to 0.
- The next largest integer between 0, 4 and 3 is 4, so we move to the right and set it to 0.
- The next largest integer between 0, 3 and 8 is 8, so we move down and set it to 0.
- The next largest integer between 3, 0, 9 and 6 is 9, so we move to the right and set it to 0.
- The next largest integer between 0, 1 and 3 is 3, so we move to the right and set it to 0.
- All neighboring integers are now 0, so we finish traversing:
[
[0, 0, 0, 0],
[1, 3, 0, 0],
[8, 3, 6, 1],
[7, 3, 5, 2]
]
- Now we add up all of the numbers that were traversed and return the result: 7 + 4 + 8 + 9 + 3 = 36