Problem Description
A matrix and a valid current position (row number and column number) are provided as input. Given a direction (RIGHT is 1, DOWN in 2, LEFT is 3 and UP is 4) and number of steps to move, output the values along the path taken to the new position, including the value at the new position.
If any position during traversal is out of bounds, output a single -1 and not the values along the path.
Code
function matrixTraversal(matrix, currPosRow, currPosCol, dirToMove, stepsToMove) {
const M = matrix.length;
const N = matrix[0].length;
let x = currPosRow, y = currPosCol;
// Directions: RIGHT, DOWN, LEFT, UP
const dx = [0, 1, 0, -1];
const dy = [1, 0, -1, 0];
let result = [];
// Check if the starting position is out of bounds
if (x < 0 || x >= M || y < 0 || y >= N) {
return "-1";
}
// Traverse for the given number of steps
for (let step = 0; step <= stepsToMove; step++) {
if (x < 0 || x >= M || y < 0 || y >= N) {
return "-1";
}
result.push(matrix[x][y].toString());
x += dx[dirToMove - 1];
y += dy[dirToMove - 1];
}
return result.join(" ");
}
tried rewrite and everytime getting the wrong output
Prashant Shukla is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.