You have to visit all cells is n*m grid, you can only visit each cell only once and you have to visit them is such a way such that when moving from one cell to another cell, the vector(mathematically speaking) (i.e. ordered_pair(dx,dy)) is never used again for any other moves. There could be other solutions as well but I am particularly interested in why this solution works. This question is from codeforces https://codeforces.com/contest/1180/problem/D
#include<bits/stdc++.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
int st=0,end=n*m-1;
for(int i=0;i<n*m;i++) {
if(i%2==0) {
cout<<st/m+1<<' '<<st%m+1<<endl;
st++;
}
else {
cout<<end/m+1<<' '<<end%m+1<<endl;
end--;
}
}
}