|
| 1 | +/* |
| 2 | +Spirally traversing a matrix |
| 3 | +============================ |
| 4 | +
|
| 5 | +Given a matrix of size R*C. Traverse the matrix in spiral form. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: |
| 9 | +R = 4, C = 4 |
| 10 | +matrix[][] = {{1, 2, 3, 4}, |
| 11 | + {5, 6, 7, 8}, |
| 12 | + {9, 10, 11, 12}, |
| 13 | + {13, 14, 15,16}} |
| 14 | +Output: |
| 15 | +1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: |
| 19 | +R = 3, C = 4 |
| 20 | +matrix[][] = {{1, 2, 3, 4}, |
| 21 | + {5, 6, 7, 8}, |
| 22 | + {9, 10, 11, 12}} |
| 23 | +Output: |
| 24 | +1 2 3 4 8 12 11 10 9 5 6 7 |
| 25 | +
|
| 26 | +Your Task: |
| 27 | +You dont need to read input or print anything. Complete the function spirallyTraverse() that takes matrix, R and C as input parameters and returns a list of integers denoting the spiral traversal of matrix. |
| 28 | +
|
| 29 | +Expected Time Complexity: O(R*C) |
| 30 | +Expected Auxiliary Space: O(R*C) |
| 31 | +
|
| 32 | +Constraints: |
| 33 | +1 <= R, C <= 100 |
| 34 | +0 <= matrixi <= 100 |
| 35 | +*/ |
| 36 | + |
| 37 | +vector<int> spirallyTraverse(vector<vector<int>> matrix, int r, int c) |
| 38 | +{ |
| 39 | + int count = r * c; |
| 40 | + vector<int> ans; |
| 41 | + int tl = 0, tr = c - 1, lt = 0, lb = r - 1; |
| 42 | + while (count > 0) |
| 43 | + { |
| 44 | + |
| 45 | + for (int i = tl; i <= tr && count > 0; ++i) |
| 46 | + { |
| 47 | + ans.push_back(matrix[lt][i]); |
| 48 | + count--; |
| 49 | + } |
| 50 | + lt++; |
| 51 | + if (count <= 0) |
| 52 | + break; |
| 53 | + |
| 54 | + for (int i = lt; i <= lb && count > 0; ++i) |
| 55 | + { |
| 56 | + ans.push_back(matrix[i][tr]); |
| 57 | + count--; |
| 58 | + } |
| 59 | + tr--; |
| 60 | + if (count <= 0) |
| 61 | + break; |
| 62 | + |
| 63 | + for (int i = tr; i >= tl && count > 0; --i) |
| 64 | + { |
| 65 | + ans.push_back(matrix[lb][i]); |
| 66 | + count--; |
| 67 | + } |
| 68 | + lb--; |
| 69 | + if (count <= 0) |
| 70 | + break; |
| 71 | + |
| 72 | + for (int i = lb; i >= lt && count > 0; --i) |
| 73 | + { |
| 74 | + ans.push_back(matrix[i][tl]); |
| 75 | + count--; |
| 76 | + } |
| 77 | + tl++; |
| 78 | + if (count <= 0) |
| 79 | + break; |
| 80 | + } |
| 81 | + return ans; |
| 82 | +} |
0 commit comments