What is a good algorithm for traversing outward from a point on a 2D grid?

Viewed 174

Suppose I have a 2D array where 0,0 is in the top left corner and the bottom is say 100,100. I have a point in that array such as 10,10. I want to do a test on each element that is 1 away from this point so a 3x3 box. If all my tests fail I want to move out one more rectangular ring so now it would be a 5x5 box. But I want to be efficient so I don't want to test the 3x3 box again just the new boxes. I've thought of maybe having a starting vector like up and then moving in a snake like pattern clockwise until I come back around then incrementing and doing it again but I'm not sure if that's the best. I've also thought of just scanning left to right but I don't want to scan row 8,8 if the answer was already found in row 9,9.

A grid would look something like this with the starting point in the middle

8,8   9,8   10,8   11,8   12,8
8,9   9,9   10,9   11,9   12,9
8,10  9,10  10,10  11,10  12,10
8,11  9,11  10,11  11,11  12,11
8,12  9,12  10,12  11,12  12,12

This is just for a cover checking algorithm for a hobby game I'm working on. In my example I've already found a source of cover at 10,10. Now I just want to search all the squares around it and test if the player can see me, and if not then I've found a good spot on my grid to hide.

1 Answers

enter image description here

Suppose you start at the red square (i,j) and need to check for a cover. You need to do what you are asking for. Check each surrounding rectangle.

Start from index (i-1, j-1). Do a test on the green squares. If not found, start from index (i-2, j-2). Do a test on the blue squares. If not found, start from index (i-3, j-3). Do a test on the yellow squares.

In some cases, instead of (i-1, j-1) you might have to go for (i-1, j) or (i, j-1).

enter image description here

enter image description here

The algorithm is not tricky here, but implementation is. Don't cross the matrix borders.

Relevant links:

  1. Print a given matrix in spiral form
  2. Construct a matrix with numbers 1 to m*n in spiral way

The above links have inward spiral. You need to similarly do for outward spiral.

Related