views:

194

answers:

2

Possible Duplicate:
Looping in a spiral

Given a grid of any height and width, write an algorithm to traverse it in a spiral. (Starting at the top left and ending in the middle) without passing over previously visited nodes. Without using nested loops.

+2  A: 
  1. Set xmin = 0, xmax = grid.width - 1, ymin = 0, and ymax = grid.height - 1. These are the traversal limits.
  2. Set dy = 0 and dx = 1. This is the traversal direction.
  3. Set x = 0 and y = 0. This is your cursor.

While xmin <= xmax and ymin <= ymax:

  1. Visit the node at (x, y).
  2. If dx == 1 and x == xmax, set dx = 0, dy = 1, and ymin = y + 1.
  3. If dy == 1 and y == ymax, set dx = -1, dy = 0, and xmax = x - 1.
  4. If dx == -1 and x == xmin, set dx = 0, dy = -1, and ymax = y - 1.
  5. If dy == -1 and y == ymin, set dx = 1, dy = 0, and xmin = x + 1.
  6. 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.

Mike DeSimone
this isn't giving me the correct stuff
garbagecollector
A: 

it should be done using one for loop and starting from bottom left, I'am in that coarse

David