Hello,↵
↵
I was wondering if there's any trick that allows us to iterate over the boundary of an $N \times M$ grid using a single loop instead of 4 or 2.↵
↵
To iterate over the whole grid for example we can iterate from 0 to $NM$ and have $i = x / M$ and $j = x \% M$.↵
↵
So is there any smart thing like this to do for the boundary only (i.e pairs $(i, j)$ such that either $i = 0$ or $i = N - 1$ or $j = 0$ or $j = M - 1$)↵
↵
Thanks for future help!↵
↵
EDIT: Problem Solved!↵
↵
<spoiler summary = "Solution 1"> ↵
Proposed by: [user:under_score_07,2021-11-11]↵
~~~~~↵
int x=0,y=1,i=0,j=0;↵
while(1)↵
{↵
cout<<i<<" "<<j<<endl;↵
if(x==0 and y==1)↵
{↵
if(j==m-1)↵
x=1,y=0;↵
}↵
else if(x==1 and y==0)↵
{↵
if(i==n-1)↵
x=0,y=-1;↵
}↵
else if(x==0 and y==-1)↵
{↵
if(j==0)↵
x=-1,y=0;↵
}↵
i+=x,j+=y;↵
if(i==0 and j==0)↵
break;↵
}↵
}↵
~~~~~↵
</spoiler>↵
↵
<spoiler summary = "Solution 2">↵
Proposed by: [user:bthero,2021-11-11]↵
~~~~~↵
bool inside(int x, int y) {↵
return 0 <= x && x < n && 0 <= y && y < m;↵
}↵
↵
int dx[] = {0, 1, 0, -1};↵
int dy[] = {1, 0, -1, 0};↵
↵
int x = 0, y = 0, d = 0;↵
↵
do {↵
// do stuff with (x, y)↵
↵
if (!inside(x + dx[d], y + dy[d])) {↵
d++;↵
}↵
↵
x += dx[d];↵
y += dy[d];↵
}↵
while (x != 0 || y != 0);↵
~~~~~↵
</spoiler>↵
↵
<spoiler summary = "My Solution inspired by the previous one">↵
~~~~~↵
for(int x = 0; x < n * m; x++) {↵
int i = x / m, j = x % m;↵
cout << i << ' ' << j << '\n';↵
x += (m - 2) * (m != 1 && i != 0 && i != n - 1 && j == 0);↵
}↵
~~~~~↵
</spoiler>↵
↵
↵
I was wondering if there's any trick that allows us to iterate over the boundary of an $N \times M$ grid using a single loop instead of 4 or 2.↵
↵
To iterate over the whole grid for example we can iterate from 0 to $NM$ and have $i = x / M$ and $j = x \% M$.↵
↵
So is there any smart thing like this to do for the boundary only (i.e pairs $(i, j)$ such that either $i = 0$ or $i = N - 1$ or $j = 0$ or $j = M - 1$)↵
↵
Thanks for future help!↵
↵
EDIT: Problem Solved!↵
↵
<spoiler summary = "Solution 1"> ↵
Proposed by: [user:under_score_07,2021-11-11]↵
~~~~~↵
int x=0,y=1,i=0,j=0;↵
while(1)↵
{↵
cout<<i<<" "<<j<<endl;↵
if(x==0 and y==1)↵
{↵
if(j==m-1)↵
x=1,y=0;↵
}↵
else if(x==1 and y==0)↵
{↵
if(i==n-1)↵
x=0,y=-1;↵
}↵
else if(x==0 and y==-1)↵
{↵
if(j==0)↵
x=-1,y=0;↵
}↵
i+=x,j+=y;↵
if(i==0 and j==0)↵
break;↵
}↵
}↵
~~~~~↵
</spoiler>↵
↵
<spoiler summary = "Solution 2">↵
Proposed by: [user:bthero,2021-11-11]↵
~~~~~↵
bool inside(int x, int y) {↵
return 0 <= x && x < n && 0 <= y && y < m;↵
}↵
↵
int dx[] = {0, 1, 0, -1};↵
int dy[] = {1, 0, -1, 0};↵
↵
int x = 0, y = 0, d = 0;↵
↵
do {↵
// do stuff with (x, y)↵
↵
if (!inside(x + dx[d], y + dy[d])) {↵
d++;↵
}↵
↵
x += dx[d];↵
y += dy[d];↵
}↵
while (x != 0 || y != 0);↵
~~~~~↵
</spoiler>↵
↵
<spoiler summary = "My Solution inspired by the previous one">↵
~~~~~↵
for(int x = 0; x < n * m; x++) {↵
int i = x / m, j = x % m;↵
cout << i << ' ' << j << '\n';↵
x += (m - 2) * (m != 1 && i != 0 && i != n - 1 && j == 0);↵
}↵
~~~~~↵
</spoiler>↵
↵