Skip to content

Instantly share code, notes, and snippets.

@comzyh
Created April 22, 2019 04:38
Show Gist options
  • Save comzyh/21ce95a3e8ed0395752a04e975ec0488 to your computer and use it in GitHub Desktop.
Save comzyh/21ce95a3e8ed0395752a04e975ec0488 to your computer and use it in GitHub Desktop.
zigzag
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
void zigzag(int m, int n) {
vector<vector<int> > ground(m);
for (size_t i = 0; i < m; i++) {
ground[i].resize(n);
}
int r = 0, c = 0;
int index = 1;
for (int i = 0; i < m + n - 1; i++) {
while(r >= 0 && c >= 0 && r < m && c < n) {
ground[r][c] = index ++;
if (i % 2) {
r ++;
c --;
} else {
r --;
c ++;
}
}
if (c >= n) {
c = n - 1;
r += 2;
}
if (r >= m) {
r = m - 1;
c += 2;
}
if (r < 0) {
r = 0;
}
if (c < 0) {
c = 0;
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%4d ", ground[i][j]);
}
printf("\n");
}
}
int main() {
int m, n;
while(cin >> m >> n) {
zigzag(m, n);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment