Given a 2D matrix of numbers, return a spiral traversal of the matrix in the clockwise direction.
In the iterative solution, we are going to traverse the matrix Row wise and Column wise, covering all the elements.
We declare 4 pointers
startRow - 0startCol - 0endRow - arr.length - 1endCol - arr[0].length - 1These pointers denote the starting and ending of columns and rows in the matrix. Moving these pointers and storing the results in an array will be our primary approach.
startRow <= endRow && startCol <= endCol, We iterate over the first row, then the last column, then the last row, then the first column. This will ensure that we cover all the boundries of the matrix and push it into the array in a clockwise direction.Top Row, Iterate from startCol to endCol - push the row elements in the array i.e. arr[startRow][i].Right Column, Iterate from the startRow to endRow - push the column elements in the array i.e. arr[i][endCol].Bottom Row, Iterate from the endCol to startCol - Push the row elements in the array. i.e. arr[endRow][i]Left Column, Iterate from endRow to startRow - Push the column elements in the array. i.e. arr[i][startCol]At every step, we decrement end indices and increment start indices because after covering the boundries of the matrix, we need to get one level deeper to print out the remaining elements.
Return the results array after the while loop breaks.
O(n^2) - Because we have to iterate over all the elements (while loop and for loop)This approach is pretty much the same as the Iterative Approach in terms of the logic, the only thing that differes is how we step into the nested levels of the matrix.
We create a helper function that has the start and the end indices of Rows and columns.
spiralTraversalRecursiveHelper(
arr,
startRow,
endRow,
startCol,
endCol,
result
);
The base condition of the recursion will be if (startRow > endRow || startCol > endCol). This is where we need to return.
We declare 4 pointers
startRow - 0startCol - 0endRow - arr.length - 1endCol - arr[0].length - 1These pointers denote the starting and ending of columns and rows in the matrix. Moving these pointers and storing the results in an array will be our primary approach.
Top Row, Iterate from startCol to endCol - push the row elements in the array i.e. arr[startRow][i].Right Column, Iterate from the startRow to endRow - push the column elements in the array i.e. arr[i][endCol].Bottom Row, Iterate from the endCol to startCol - Push the row elements in the array. i.e. arr[endRow][i]Left Column, Iterate from endRow to startRow - Push the column elements in the array. i.e. arr[i][startCol].helper function to get one level deeper into the matrix.At every step, we decrement end indices and increment start indices because after covering the boundries of the matrix, we need to get one level deeper to print out the remaining elements.