Skip to content

Instantly share code, notes, and snippets.

@sturgle
Created January 29, 2015 06:28
Show Gist options
  • Save sturgle/003c5031152936f4492b to your computer and use it in GitHub Desktop.
Save sturgle/003c5031152936f4492b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <sstream>
#include <utility>
using namespace std;
void getNextPoint(pair<int, int> &point, int m , int n, int &dir) {
int x = point.first;
int y = point.second;
if (dir == 1) {
if (y == n - 1) {
point.first++;
dir = -1;
} else if (x == 0) {
point.second++;
dir = -1;
} else {
point.first--;
point.second++;
}
} else {
if (x == m - 1) {
point.second++;
dir = 1;
} else if (y == 0) {
point.first++;
dir = 1;
} else {
point.first++;
point.second--;
}
}
}
vector<vector<int> > snakeMatrix(int m, int n) {
vector<vector<int> > matrix(m, vector<int>(n));
pair<int, int> point(0, 0);
int dir = 1;
for (int i = 0; i < m * n; i++) {
matrix[point.first][point.second] = i + 1;
getNextPoint(point, m, n, dir);
}
return matrix;
}
void printSnakeMatrix(int m, int n) {
cout << "matrix " << m << " * " << n << ": " << endl;
vector<vector<int> > v = snakeMatrix(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << v[i][j] << ", ";
}
cout << endl;
}
}
int main() {
printSnakeMatrix(3, 3);
printSnakeMatrix(4, 4);
printSnakeMatrix(3, 1);
printSnakeMatrix(3, 4);
printSnakeMatrix(3, 6);
printSnakeMatrix(3, 7);
printSnakeMatrix(4, 1);
printSnakeMatrix(4, 3);
printSnakeMatrix(4, 8);
printSnakeMatrix(4, 9);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment