0

I wanna make some code that search all route in 5 * 5 board, that have to satisfy those conditions below.

  1. cannot search the position already searched
  2. search all positions in the board
  3. you can start searching anywhere in the board

so I wrote a code below...but it doesn't work. It stopped searching when first search is completed, and the dfs didn't work recursively.

I think when the first search is completed (like ㄴㅣㅕㅇㅔㅐㅇㅏㄴㅣㄴㄱ?ㅑㅗㅐㄸㅜㄸㄹㄹㅏㄱㄴㄱ first), the 'route' variable doesn't initialized. so when the first search is finished, all elements in route is still 1 and next recursive search is cannot started. but I cannot find the reason of this problem.

board = [['ㄴ','ㅣ','ㅕ','ㅇ','ㅔ'],['ㅏ', 'ㄱ', 'ㄴ', 'ㄱ', 'ㅐ'],
         ['ㄹ', 'ㄹ', 'ㄸ', 'ㅜ', 'ㅇ'],['ㅑ', 'ㅗ', 'ㅐ', 'ㄸ', 'ㅏ'],
         ['?', 'ㄱ',  'ㄴ',  'ㅣ', 'ㄴ']]

# plz don't mind about Korean characters lol


result_list = []

def dfs(row, col, route, sent): 
    # row, col : row, column of current position
    # route : type - double list (5 * 5). each element goes to 1 when searched
    # sent : string made by searched character so far

    sent += board[row][col] # add char of current position
    route[row][col] = 1 # mark current position (turn from 0 to 1 of corresponding element)

    if len(sent) == 25: # when it finished to search all element
        result_list.append(sent) # append the string to result_list
        return # exit function
    
    dx = [0, 1, 0, -1] # to move row-direction
    dy = [1, 0, -1, 0] # to move col-direction

    for i in range(4):
        row_next = row + dx[i] # new position of row : current position + change of row
        col_next = col + dy[i] # same to col

        if 0 <= row_next < 5 and 0 <= col_next < 5: # if new positon is in the 5 * 5 board
            if route[row_next][col_next] == 0: # if new position is not already searched
                dfs(row_next, col_next, route, sent) # search recursively

initial_route = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
# initial route (all elements are not searched)

for i in range(5):
    for j in range(5):
        dfs(i, j, initial_route, '')
        # search for every position
  • You don't ever clear the `route` grid. Is your rule that you can't search any position that has been searched *ever*, or only any position that has been searched *in the current path*? – Samwise Sep 07 '21 at 14:55
  • In the current path. I cannot find how to clear route grid without any bug.... trying to. – HealingMusic Sep 08 '21 at 11:16
  • Each recursive call to `dfs` needs to clear the cell that it set before it returns. I.e. do `route[row][col] = 0` before your `return`, and also before the implicit return at the very end of the function (after the loop with the recursive calls). – Samwise Sep 08 '21 at 14:44

0 Answers0