Skip to content

Commit a1c8649

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 60b8388 commit a1c8649

File tree

4 files changed

+53
-10
lines changed

4 files changed

+53
-10
lines changed

0054_spiral_matrix/spiral_matrix.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4+
45
/**
56
** Note: The returned array must be malloced, assume caller calls free().
67
**/
7-
static int* spiralOrder(int** matrix, int matrixSize, int *matrixColSize, int *returnSize)
8+
int* spiralOrder(int** matrix, int matrixSize, int *matrixColSize, int *returnSize)
89
{
910
if (matrixSize == 0) {
1011
*returnSize = 0;

0054_spiral_matrix/spiral_matrix.cc

+3-8
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,12 @@ using namespace std;
55
class Solution {
66
public:
77
vector<int> spiralOrder(vector<vector<int>>& matrix) {
8-
if (matrix.empty()) {
9-
return vector<int>();
10-
}
11-
8+
vector<int> res;
129
int hor_top = 0;
13-
int hor_bottom = matrix.size();
10+
int hor_bottom = matrix.size() - 1;
1411
int ver_left = 0;
15-
int ver_right = matrix[0].size();
12+
int ver_right = matrix[0].size() - 1;
1613
int direction = 0;
17-
vector<int> res;
18-
1914
while (hor_top <= hor_bottom && ver_left <= ver_right) {
2015
switch (direction) {
2116
case 0:

0059_spiral_matrix_ii/spiral_matrix.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* The sizes of the arrays are returned as *returnColumnSizes array.
88
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
99
*/
10-
static int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
10+
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
1111
{
1212
int i;
1313
int **matrix = malloc(n * sizeof(int *));
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
vector<vector<int>> generateMatrix(int n) {
8+
vector<vector<int>> matrix(n, vector<int>(n));
9+
int direction = 0;
10+
int hor_top = 0;
11+
int hor_bottom = n - 1;
12+
int ver_left = 0;
13+
int ver_right = n - 1;
14+
int num = 0;
15+
while (num < n * n) {
16+
switch (direction) {
17+
case 0:
18+
for (int i = ver_left; i <= ver_right; i++) {
19+
matrix[hor_top][i] = ++num;
20+
}
21+
hor_top++;
22+
break;
23+
case 1:
24+
for (int i = hor_top; i <= hor_bottom; i++) {
25+
matrix[i][ver_right] = ++num;
26+
}
27+
ver_right--;
28+
break;
29+
case 2:
30+
for (int i = ver_right; i >= ver_left; i--) {
31+
matrix[hor_bottom][i] = ++num;
32+
}
33+
hor_bottom--;
34+
break;
35+
case 3:
36+
for (int i = hor_bottom; i >= hor_top; i--) {
37+
matrix[i][ver_left] = ++num;
38+
}
39+
ver_left++;
40+
break;
41+
}
42+
direction++;
43+
direction %= 4;
44+
}
45+
return matrix;
46+
}
47+
};

0 commit comments

Comments
 (0)