Created
September 24, 2019 22:20
-
-
Save adamkorg/7e4a25b9b5961e0f133e9d2f6d23a948 to your computer and use it in GitHub Desktop.
Leetcode 59: Spiral Matrix II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
void addLayer(vector<vector<int>>& m, int layer) { | |
int n = m.size(); | |
int val = 0; //last value | |
if (layer > 0) | |
val = m[layer][layer-1]; | |
for (int r=layer,c=layer; c<n-layer; ++c) //fill right -> | |
m[r][c] = ++val; | |
for (int r=layer+1,c=n-1-layer; r<n-layer; ++r) //fill down v | |
m[r][c] = ++val; | |
for (int r=n-1-layer,c=n-1-1-layer; c>=0+layer; --c) //fill left <- | |
m[r][c] = ++val; | |
for (int r=n-1-1-layer,c=layer; r>layer; --r) //fill up ^ | |
m[r][c] = ++val; | |
} | |
vector<vector<int>> generateMatrix(int n) { | |
if (n <= 0) | |
return {}; | |
vector<vector<int>> m(n, vector<int>(n,0)); | |
int layers = (n+1)/2; | |
for (int i=0; i<layers; ++i) | |
addLayer(m, i); | |
return m; | |
} | |
void printv(const vector<vector<int>>& m) { | |
for (int r=0; r<m.size(); ++r) { | |
for (int c=0; c<m[r].size(); ++c) | |
cout << (m[r][c]<10?" ":"") << m[r][c] << " "; | |
cout << "\n"; | |
} | |
cout << "\n"; | |
} | |
int main() { | |
auto m = generateMatrix(5); | |
printv(m); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment