Продолжить итерацию 2D-массива из определенного элемента

Я создаю игру для поиска слов, и я застрял в алгоритме. Мне нужно найти вхождения слова в таблицу, как структура данных. Я решил использовать 2d массив, для которого я знаю длину и высоту. Моя идея состоит в том, чтобы искать первую букву слова и, если найден, искать во всех возможных направлениях. Я не могу понять, как начать поиск после того, как я нашел первую букву. Я хочу передать местоположение первой буквы методам, которые будут искать во всех направлениях. Вот что у меня так далеко:

 public void SearchWord(char[,] input, string name)
    {
        //1. loop through the array and look for the first letter of the string
        //2. if found search in all directions "iterative"
        //3. if one direction doesn't find it break out of the method and continue to search in other directions
        //4. if found mark the positions so you don't find the same word more than once
        char firstLetter = name[0];

        //go look for it in the 2d array
        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 4; x++)
            {
                if (results[x, y] == firstLetter)//found the letter
                {
                    Console.WriteLine("Found it " + " " + firstLetter);
                    Console.WriteLine(x + " " + y);
                    SearchRightDirection(x, y);
                    SearchLeftDirection(x, y);

                }
            }
        }
    }

Я попытался передать местоположение в качестве параметра, подобного SearchRightDirection(char[,], int x, int y){}, однако я не могу продолжить с этой строки точного местоположения и столбца массива.

Есть ли у вас предложения? Также, если структура является правильной?

1 ответ

Решение

Ну вот:

public static class Sample
{
    public static int CountOccurrences(char[,] table, string word)
    {
        if (string.IsNullOrEmpty(word)) return 0;
        int count = 0;
        int rowCount = table.GetLength(0);
        int colCount = table.GetLength(1);
        for (int row = 0; row < rowCount; row++)
        {
            for (int col = 0; col < colCount; col++)
            {
                if (table[row, col] != word[0]) continue;
                if (word.Length == 1) { count++; continue; }
                for (int dy = -1; dy <= 1; dy++)
                    for (int dx = -1; dx <= 1; dx++)
                        if ((dx != 0 || dy != 0) && Match(word, table, rowCount, colCount, row, col, dy, dx)) count++;
            }
        }
        return count;
    }
    private static bool Match(string word, char[,] table, int rowCount, int colCount, int startRow, int startCol, int dy, int dx)
    {
        int row = startRow + dy;
        if (dy != 0 && (dy < 0 ? row : rowCount - row) < word.Length - 1) return false;
        int col = startCol + dx;
        if (dx != 0 && (dx < 0 ? col : colCount - col) < word.Length - 1) return false;
        for (int charPos = 1; charPos < word.Length; row += dy, col += dx, charPos++)
            if (table[row, col] != word[charPos]) return false;
        return true;
    }
}
Другие вопросы по тегам