I wanna make some code that search all route in 5 * 5 board, that have to satisfy those conditions below.
- cannot search the position already searched
- search all positions in the board
- 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