Skip to content

Instantly share code, notes, and snippets.

@justinmeiners
Last active October 27, 2022 19:36
Show Gist options
  • Save justinmeiners/af58cea12ca476b73d9b195038c4f0f0 to your computer and use it in GitHub Desktop.
Save justinmeiners/af58cea12ca476b73d9b195038c4f0f0 to your computer and use it in GitHub Desktop.
How to iterate neighbors of a grid efficiently and concisely.
#include <algorithm>
template <typename I>
void rotate_2d(I& a, I& b) {
std::swap(a, b);
b = -b;
}
int main() {
// Suppose we want to iterate over the neighbors of a cell in a 2D grid:
// * * *
// * - *
// * * *
// This can be done with the following loop:
printf("diagonal\n");
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (i == j) continue;
printf("%d, %d\n", i, j);
}
}
// But what if just want the directly adjacent cells and ignore diagonal cells?
// *
// * - *
// *
// This is a little tricker, but the idea is just to
// rotate one neighbor around the center cell, 4 times.
printf("square\n");
{
int i = 1;
int j = 0;
for (int k = 0; k < 4; ++k) {
printf("%d, %d\n", i, j);
rotate_2d(i, j);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment