Traversing 2D Arrays in PHP With Conditional Moves
Introduction
Hello, and welcome back to our coding lesson series. In this unit, we have a fascinating problem at hand that uses the concept of 2D arrays or grids in PHP. What's interesting about this problem is that it involves not only the simple traversal of the grid but also making this traversal in a unique manner. Initially, the concept might seem a bit tricky, but as we dissect the task and take it step by step, you're sure to enjoy how it unfolds. Are you ready to embark on this adventure? Let's dive right in!
Task Statement
Solution Building: Step 1
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
The task before us involves the creation of a PHP function named pathTraverse. This function should perform a particularly ordered traversal through a 2D grid. The function will accept a grid represented as a 2D array and the starting cell coordinates as parameters. Starting from the provided cell, the function should move in any one of the four possible directions toward an adjacent cell. However, a condition governs this selection: the new cell value should be strictly greater than the current cell's value. Think of this as navigating a hiking trail where you can only move to higher ground from your current position.
This pattern would continue as we keep selecting the next available larger cell value. The traversal would halt when there are no cells left that satisfy our criteria. The final result of the function will be an array that includes all the visited cell values in the order of their visitation.
Consider a 3×3 grid:
1 2 34 5 67 8 9
If we start at the cell with the value 5, we can logically move to either 6 or 8. Let's say we choose 8; the only cell that we can now move to is 9. After this, we have no more moves left that fit our criteria. Hence, the function returns [5, 8, 9].
The first thing we need to do is determine the dimensions of our grid, which is relatively easy in PHP with the count() function. We can also establish the directions that our traversal can take. In the context of matrices, when we say we are moving "up," we are moving one step towards the first row (decreasing the row index). Similarly, moving "down" corresponds to moving one step towards the last row (increasing the row index), and moving left or right relates to decrementing or incrementing the column index, respectively.
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); $directions = [ [-1, 0], // Up [1, 0], // Down [0, -1], // Left [0, 1] // Right ];
In the $directions array, each pair represents a direction in terms of a pair (rowOffset, colOffset). So, if we are at a cell (r, c), moving up corresponds to going to the cell (r-1, c), moving down corresponds to (r+1, c), moving left corresponds to (r, c-1), and moving right corresponds to (r, c+1).
Solution Building: Step 2
Once we have the grid's dimensions and the possible directions, we should validate the starting point and set up our visited cell recording mechanism.
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); // Check the validity of the input if ($startRow < 0 || $startRow >= $rows || $startCol < 0 || $startCol >= $cols) { echo "Invalid input\n"; return []; } // Define all four possible directions of movement $directions = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; // Start with the value at the starting cell $visited = []; $visited[] = $grid[$startRow][$startCol];
Solution Building: Step 3
Let's initiate the grid traversal process in our function. We first set up an infinite loop that will only stop when we break it based on a condition. Inside the infinite loop, for each iteration, we'll have the function try to select the next cell with the maximum value among the adjacent cells. If we find such a cell, we'll capture its value, and it will be our next cell.
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); // Check the validity of the input if ($startRow < 0 || $startRow >= $rows || $startCol < 0 || $startCol >= $cols) { echo "Invalid input\n"; return []; } // Define all four possible directions of movement $directions = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; // Start with the value at the starting cell $visited = []; $visited[] = $grid[$startRow][$startCol]; while (true) { // Initialize the current maximum as negative one $currMax = -1; $nextRow = -1; $nextCol = -1; // Loop over each adjacent cell in all the directions foreach ($directions as $dir) { // Calculate the new cell's row and column indices $newRow = $startRow + $dir[0]; $newCol = $startCol + $dir[1]; // If the new cell is out of the grid boundary, ignore it if ($newRow < 0 || $newRow >= $rows || $newCol < 0 || $newCol >= $cols) { continue; } // If the new cell's value is greater than the current maximum if ($grid[$newRow][$newCol] > $currMax) { // Save it as the next cell to visit $nextRow = $newRow; $nextCol = $newCol; $currMax = $grid[$newRow][$newCol]; } } // If we don't have any valid cell to visit, break from the loop if ($currMax <= $grid[$startRow][$startCol]) { break; } // Otherwise, go to the next cell $startRow = $nextRow; $startCol = $nextCol; // Append the cell's value to the result list $visited[] = $currMax; } // Return the list of visited cells' values return $visited;}// Example usage$grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]];$res = pathTraverse($grid, 1, 1);foreach ($res as $val) { echo $val . ' ';}echo PHP_EOL;
Lesson Summary
Bravo! You've successfully solved a complex problem involving the traversal of a grid in a unique pattern using PHP. This function has tested not only your skills in PHP programming but also your ability to visualize spatial patterns.
Having digested this knowledge, it's now time to test your understanding and apply these concepts to similar problems. Watch out for the ensuing practice session, where you can dabble with more challenging problems and refine your problem-solving skills. Keep up the good work and happy coding!
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); $directions = [ [-1, 0], // Up [1, 0], // Down [0, -1], // Left [0, 1] // Right ];
PHP
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); // Check the validity of the input if ($startRow < 0 || $startRow >= $rows || $startCol < 0 || $startCol >= $cols) { echo "Invalid input\n"; return []; } // Define all four possible directions of movement $directions = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; // Start with the value at the starting cell $visited = []; $visited[] = $grid[$startRow][$startCol];
PHP
<?phpfunction pathTraverse($grid, $startRow, $startCol) { $rows = count($grid); $cols = count($grid[0]); // Check the validity of the input if ($startRow < 0 || $startRow >= $rows || $startCol < 0 || $startCol >= $cols) { echo "Invalid input\n"; return []; } // Define all four possible directions of movement $directions = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; // Start with the value at the starting cell $visited = []; $visited[] = $grid[$startRow][$startCol]; while (true) { // Initialize the current maximum as negative one $currMax = -1; $nextRow = -1; $nextCol = -1; // Loop over each adjacent cell in all the directions foreach ($directions as $dir) { // Calculate the new cell's row and column indices $newRow = $startRow + $dir[0]; $newCol = $startCol + $dir[1]; // If the new cell is out of the grid boundary, ignore it if ($newRow < 0 || $newRow >= $rows || $newCol < 0 || $newCol >= $cols) { continue; } // If the new cell's value is greater than the current maximum if ($grid[$newRow][$newCol] > $currMax) { // Save it as the next cell to visit $nextRow = $newRow; $nextCol = $newCol; $currMax = $grid[$newRow][$newCol]; } } // If we don't have any valid cell to visit, break from the loop if ($currMax <= $grid[$startRow][$startCol]) { break; } // Otherwise, go to the next cell $startRow = $nextRow; $startCol = $nextCol; // Append the cell's value to the result list $visited[] = $currMax; } // Return the list of visited cells' values return $visited;}// Example usage$grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]];$res = pathTraverse($grid, 1, 1);foreach ($res as $val) { echo $val . ' ';}echo PHP_EOL;