- Set
xmin = 0, xmax = grid.width - 1, ymin = 0, and ymax = grid.height - 1. These are the traversal limits.
- Set
dy = 0 and dx = 1. This is the traversal direction.
- Set
x = 0 and y = 0. This is your cursor.
While xmin <= xmax and ymin <= ymax:
- Visit the node at (
x, y).
- If
dx == 1 and x == xmax, set dx = 0, dy = 1, and ymin = y + 1.
- If
dy == 1 and y == ymax, set dx = -1, dy = 0, and xmax = x - 1.
- If
dx == -1 and x == xmin, set dx = 0, dy = -1, and ymax = y - 1.
- If
dy == -1 and y == ymin, set dx = 1, dy = 0, and xmin = x + 1.
- Set
x = x + dx and y = y + dy.
I have no idea what that algorithm is called; it just seemed apparent from the description. Nested loops would be a much more optimal solution; all those if statements will push the limits of an optimizer.