0

I'd like to generate the adjacency matrix for a boggle board. A boggle board is one where you have alphabets in a nxn matrix like this: http://www.wordtwist.org/sample.gif

Each cell is connected to its neighbor cell; basically we move up/down/left/right/diagonally to connect to another cell.

If each cell is viewed as a vertex in a graph, then we can find the adjacency matrix of the boggle board.

I came up with the following formulas to find the adjacent cells: Assume the index of the cells start with 0 and are numbered from left to right. i = cell index, n = number of rows/columns. So in a 3x3 matrix, i=0 would be the first cell and n is 3.

up = i-n
down = i+n
left = i-1
right = i+1
diagonal 1 = i-(n+1), i+(n+1)
diagonal 2 = i-(n-1), i+(n-1)

The above formulas fail in case of corner cells. How to exclude the invalid cells for corner cases?

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
codewarrior
  • 984
  • 4
  • 18
  • 34

1 Answers1

1

You shouldn't have to "exclude" anything, merely check your result to see whether it is in bounds or not, if it isn't then there is no valid cell. (i.e. If you are at the top left of your 3x3 matrix (i = 0) then up (i - n) is (0 - 3 = -3). Since -3 is outside the bounds of your matrix, there is no valid cell.

So if you are doing a search and want to travel along the "up" adjacent cell, first check whether that location is in bounds, if it is not then you are at the end.

To check if you are on the left or right edge of the matrix, use:

if i % (n-1) == 0 // Right edge

if i % (n) == 0 // Left edge

NominSim
  • 8,447
  • 3
  • 28
  • 38
  • Lets say I've a 3x3 matrix, and I'm looking at the cell i=2 (the last cell in the first row). n=3 here. Then up = -1 down = 5 left = 1 right = 3 diagonal 1: -2, 6 diagonal 2: 0, 4 Out of these, we can discard -1 and -2 as they are out of bounds. Now I get (5,1,3,6,0,4) from the above calculations.However, the correct adjacent cells are just (1,5,4). I have to exclude the cells 0,3 and 6 from above. Am I doing something wrong? – codewarrior Feb 06 '13 at 22:59
  • Ah I see what you mean, well you just have to account for the sides as well. Perform the following calculations: `if i % n == 0 then` you are on the left edge and have no left cell, `if i % (n-1) == 0 then` you are on the right edge and have no right cell. – NominSim Feb 06 '13 at 23:06
  • Yup did that. In this case, i % n-1 is 0, but how do I use that to discard the values 6 and 0 but still keep 4? – codewarrior Feb 06 '13 at 23:17