0

I am looking at this article: https://www.geeksforgeeks.org/find-all-occurrences-of-the-word-in-a-matrix/?ref=lbp

and it has this function

static void DFS(char mat[][], int row, int col,
        int prevRow, int prevCol, char[] word,
        String path, int index, int n)
{
    // return if current character doesn't match with
    // the next character in the word
    if (index > n || mat[row][col] != word[index])
        return;

    // append current character position to path
    path += (word[index]) + "(" + String.valueOf(row)
            + ", " + String.valueOf(col) + ") ";

    // current character matches with the last character
    // in the word
    if (index == n)
    {
        System.out.print(path +"\n");
        return;
    }

    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k)
        if (isvalid(row + rowNum[k], col + colNum[k],
                    prevRow, prevCol))

            DFS(mat, row + rowNum[k], col + colNum[k],
                row, col, word, path, index + 1, n);

where it calls itself, is there a way around this?

c sharp
  • 25
  • 4
  • 2
    You can implement it with iteration, but you would have to maintain a stack yourself for the DFS-search to work. The recursive solution is probably much easier to understand. – marstran Jan 17 '22 at 17:21
  • General principle: https://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration –  Jan 17 '22 at 17:31

0 Answers0