Skip to content

Commit 2c475f0

Browse files
authored
Added solution for Spiral-matrix in cpp (#205)
* Create Spiral-matrix.cpp * Update README.md
1 parent e76c115 commit 2c475f0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

C++/Spiral-matrix.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//Problem Number : 54
2+
//Problem Name : Spiral Matrix
3+
//Problem Statement : Given an m x n matrix, return all elements of the matrix in spiral order.
4+
5+
class Solution {
6+
public:
7+
vector<int> spiralOrder(vector<vector<int>>& matrix) {
8+
vector<int>res;
9+
int left = 0, top = 0, down = matrix.size()-1, right = matrix[0].size()-1;
10+
11+
while(left <= right && top <= down){
12+
//From left to right on top side
13+
for(int i = left; i <= right; i++)
14+
res.push_back(matrix[top][i]);
15+
top++;
16+
//From top to down on right side
17+
for(int i = top; i <= down; i++)
18+
res.push_back(matrix[i][right]);
19+
right--;
20+
if(top <= down){
21+
//From right to left on down side
22+
for(int i = right; i >= left; i--)
23+
res.push_back(matrix[down][i]);
24+
down--;
25+
}
26+
if(left <= right){
27+
//From down to top on left side
28+
for(int i = down; i >= top; i--)
29+
res.push_back(matrix[i][left]);
30+
left++;
31+
}
32+
}
33+
return res;
34+
}
35+
};
36+
37+
//This code is contributed by Nikhil-1503

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
145145
| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Java](./Java/valid-sudoku.java) | O(N^2) | O(N) | Medium | Array, 2D Matrix |
146146
| 1512 | [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/) | [Java](./Java/Number-of-Good-Pairs.java) | O(N^2) | O(1) | Easy | Array |
147147
| 162 | [Find Peak element](https://leetcode.com/problems/find-peak-element/) | [javascript](https://github.com/codedecks-in/LeetCode-Solutions/blob/master/JavaScript/findPeakElement.js) | o(Logn) | O(1) | Medium | Array |
148+
| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/Spiral-matrix.cpp) | O(M\*N) | O(M\*N) | Medium | Array |
149+
148150

149151
<br/>
150152

0 commit comments

Comments
 (0)