how can i make my recursive function go back to continue recursing other cells?

The actual problem is you only have one list. If you want to find more than one word you need a list of lists:

if event.key == pygame.K_RETURN:
    for cell in grid.cells:
        lstlst = [[cell]]
        grid.adj(cell, 1, lstlst, word)
        for lst in lstlst:
            if ''.join([c.text for c in lst]) == word:
                print("FOUND")

When a new character is identified, you need to copy the last list of the list of lists:

taillst = lstlst[-1]
lst = taillst[:]

Append the new cell to the copy and add the copy to the end of the list of lists:

lst.append(cell)
lstlst.append(lst)

Do not increment idx, but pass idx + 1 to the next recursion level:

self.adj(cell, idx+1, lstlst, wrd)

Complete method adj:

class Grid():
    # [...]

    def adj(self, cell, idx, lstlst, wrd):
        x, y = self.cells.index(cell) // self.rows, self.cells.index(cell) % self.rows
        y1 = x - 1 if x else 0
        y2 = self.rows + 2 if x > self.rows + 2 else x + 2
        x1 = y - 1 if y else 0
        x2 = self.cols + 2 if y > self.cols + 2 else y + 2
        adjs = [cell for row in self.grid[y1:y2] for cell in row[x1:x2] if cell != self.grid[x][y]]
        taillst = lstlst[-1]
        for cell in adjs:
            if len(wrd) > idx:
                if cell.text == wrd[idx]:
                    lst = taillst[:]
                    lst.append(cell)
                    lstlst.append(lst)
                    self.adj(cell, idx+1, lstlst, wrd)

The following pattern

returns the following 6 lists with 3 matches:

['C']
['C', 'A']
['C', 'A', 'T']
['C', 'A', 'T']
['C', 'A']
['C', 'A', 'T']

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top