|
1 |
| -// Printing Matrix in spiral order |
| 1 | +/* |
| 2 | + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and |
| 3 | + returns a one-dimensional array of all the array's elements in spiral order. |
| 4 | +
|
| 5 | + Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds |
| 6 | + in a spiral pattern all the way until every element has been visited. |
| 7 | +
|
| 8 | + Explanation: |
| 9 | +
|
| 10 | + The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the |
| 11 | + elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise. |
| 12 | +
|
| 13 | + The function first initializes an empty slice result to hold the elements of the spiral traversal. |
| 14 | + If the input array is empty, the function immediately returns the empty result. |
| 15 | +
|
| 16 | + Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the |
| 17 | + boundaries of the matrix. These variables will be updated as the function traverses the matrix. |
| 18 | +
|
| 19 | + The function then enters a loop that traverses the matrix in a spiral order. The loop continues |
| 20 | + as long as startRow <= endRow and startCol <= endCol, which means that there are still elements |
| 21 | + in the matrix to be traversed. |
| 22 | +
|
| 23 | + The first step in the loop is to traverse the top row of the matrix from left to right, and append |
| 24 | + each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom, |
| 25 | + and append each element to the result slice. If there is more than one row in the matrix, the function then traverses |
| 26 | + the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left, |
| 27 | + the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix, |
| 28 | + the function traverses the left |
| 29 | +
|
| 30 | + O(n) time | O(n) space - where n is the total number of elements in the array |
| 31 | +*/ |
2 | 32 | #include<bits/stdc++.h>
|
3 | 33 | using namespace std;
|
4 | 34 |
|
|
0 commit comments