Search code examples
c++boggle

Meaning of "direction X-Y delta pairs for adjacent cells"


I'm trying to understand the game algorithm called "Boggle" which finds words in an N*N matrix.

#include <cstdio>
#include <iostream>

using namespace std;

const int N = 6; // max length of a word in the board

char in[N * N + 1]; // max length of a word
char board[N+1][N+2]; // keep room for a newline and null char at the end
char prev[N * N + 1];
bool dp[N * N + 1][N][N];

 // direction X-Y delta pairs for adjacent cells
int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};
bool visited[N][N];

bool checkBoard(char* word, int curIndex, int r, int c, int wordLen)
{
if (curIndex == wordLen - 1)
{
    //cout << "Returned TRUE!!" << endl;
    return true;
}

int ret = false;

for (int i = 0; i < 8; ++i)
{
    int newR = r + dx[i];
    int newC = c + dy[i];

    if (newR >= 0 && newR < N && newC >= 0 && newC < N && !visited[newR]        [newC] && word[curIndex+1] == board[newR][newC])

I do not understand this part:

 // direction X-Y delta pairs for adjacent cells
 int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
 int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};

Why do these array have the values they have and why does this work?


Solution

  • These arrays represent the possible combinations of row and column offsets from the current "cursor" location (which is an x,y coordinate tracked in the code as variables c,r):

     // direction X-Y delta pairs for adjacent cells
     int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
     int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};
    

    For example, if you imagine a 3x3 square grid, and consider the central box to be the current location, then the other 8 surrounding cells are those indicated by these sets of row and column offsets. If we took the offsets at index 2 (dx[2] = 1 and dy[2] = 0), this would indicate the cell one row down (and zero shifting left/right).