Lesson 5
Grid Traversal in Kotlin with Path Exploration
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. What's interesting about this problem is that it involves 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

The task before us involves the creation of a Kotlin function named pathTraverse. This function should perform a particularly ordered traversal through a 2D grid. The function will accept a grid represented as an Array<Array<Int>>, along with 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 a MutableList<Int> that includes all the visited cell values in the order of their visitation.

Consider a 3x3 grid:

Plain text
11 2 3 24 5 6 37 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 6; 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, 6, 9}.

Solution Building: Step 1

The first thing we need to do is determine the dimensions of our grid, which is relatively easy in Kotlin using property accessors. 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.

Kotlin
1fun pathTraverse(grid: Array<Array<Int>>, startRow: Int, startCol: Int): MutableList<Int> { 2 val rows = grid.size 3 val cols = grid[0].size 4 val directions = arrayOf( 5 intArrayOf(-1, 0), // Up 6 intArrayOf(1, 0), // Down 7 intArrayOf(0, -1), // Left 8 intArrayOf(0, 1) // Right 9 )

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.

Kotlin
1fun pathTraverse(grid: Array<Array<Int>>, startRow: Int, startCol: Int): MutableList<Int> { 2 val rows = grid.size 3 val cols = grid[0].size 4 5 // Check the validity of the input 6 if (startRow < 0 || startRow >= rows || startCol < 0 || startCol >= cols) { 7 println("Invalid input") 8 return mutableListOf() 9 } 10 11 // Define all four possible directions of movement 12 val directions = arrayOf( 13 intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(0, 1) 14 ) 15 16 // Start with the value at the starting cell 17 val visited = mutableListOf<Int>() 18 visited.add(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.

Kotlin
1fun pathTraverse(grid: Array<Array<Int>>, startRow: Int, startCol: Int): MutableList<Int> { 2 val rows = grid.size 3 val cols = grid[0].size 4 5 // Check the validity of the input 6 if (startRow < 0 || startRow >= rows || startCol < 0 || startCol >= cols) { 7 println("Invalid input") 8 return mutableListOf() 9 } 10 11 // Define all four possible directions of movement 12 val directions = arrayOf( 13 intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(0, 1) 14 ) 15 16 // Start with the value at the starting cell 17 val visited = mutableListOf<Int>() 18 visited.add(grid[startRow][startCol]) 19 20 var currentRow = startRow 21 var currentCol = startCol 22 23 while (true) { 24 // Initialize the current maximum as current cell value 25 var currMax = grid[currentRow][currentCol] 26 var nextRow = -1 27 var nextCol = -1 28 29 // Loop over each adjacent cell in all the directions 30 for (dir in directions) { 31 // Calculate the new cell's row and column indices 32 val newRow = currentRow + dir[0] 33 val newCol = currentCol + dir[1] 34 35 // If the new cell is in the grid boundary and has a higher value 36 if (newRow in 0 until rows && newCol in 0 until cols && grid[newRow][newCol] > currMax) { 37 // Save it as the next cell to visit 38 nextRow = newRow 39 nextCol = newCol 40 currMax = grid[newRow][newCol] 41 } 42 } 43 44 // If we don't have any valid cell to visit, break from the loop 45 if (nextRow == -1) break 46 47 // Otherwise, go to the next cell 48 currentRow = nextRow 49 currentCol = nextCol 50 51 // Append the cell's value to the result list 52 visited.add(currMax) 53 } 54 55 // Return the list of visited cells' values 56 return visited 57} 58 59fun main() { 60 val grid = arrayOf( 61 arrayOf(1, 2, 3), 62 arrayOf(4, 5, 6), 63 arrayOf(7, 8, 9) 64 ) 65 val res = pathTraverse(grid, 1, 1) 66 for (value in res) { 67 print("$value ") 68 } 69 // Expected output: 5 8 9 70}
Lesson Summary

Bravo! You've successfully solved a complex problem involving the traversal of a grid in a unique pattern. This function has tested not only your skills in Kotlin 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. Kotlin's expressive syntax and robust type system aid in developing these elegant solutions effectively. Keep up the good work and happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.