How to generate an "adjacency matrix" dynamically depending on grid size?

264 Views Asked by At

I am doing a BoggleBoard game for a coding bootcamp that includes a function to take words and check if they exist on the board. My method in checking to see if the word existed was to create what I called an "adjacency matrix" (I understand that this isn't an actual adjacency matrix, this is something I came up with rather chaining through the actual locations of the letters I was searching for). The idea on a 3x3 grid is:

0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

Corresponding "adjacency matrix" is:

[ [1,3,4],
  [0,2,3,4,5],
  [1,4,5],
  [0,1,4,6,7],
  [0,1,2,3,5,6,7,8],
  [1,2,4,7,8],
  [3,4,7],
  [3,4,5,6,8],
  [4,5,7]
]

The idea is that rather than actually having to locate the word on the board, I create a separate array corresponding to the length of letters of the word. Each letter of the word has an array within the array showing the index of everywhere the word appears on the board. I then basically check to see if the cells adjacent to the current letter per the adjacency matrix share an index with the locations of the following character.

Example: Board:
C | A
C | T

Searching for: CAT

letter_locations = [[0,2],[1],[3]]
Adjacency matrix = 
    [[1,2,3],
    [0,2,3],
    [0,1,3],
    [0,1,2]]

Index of first character, C, = 0
- Cells adjacent to index 0 = concatenate [1,2,3] and [0,1,3] => [0,1,2,3]
- Letter A occurs at either 0,1,2,3? Yes
- Proceed
Index of next character, A, = 1
- Cells adjacent to index 1 = 0,2,3
- Letter T occurs at either 0,2,3? Yes
Word found

I currently have the game set up for a 4x4 grid of game play and have hard-coded in an adjacency matrix. I would like to see if there is a way to make the game size the board based off user input and dynamically create an adjacency matrix depending on the size of the board. Is this possible?

(I understand that this isn't an actual adjacency matrix, this is something I came up with rather chaining through the actual locations of the letters I was searching for.)

0

There are 0 best solutions below