I have designed a algorithm which will solve the 8 square problem using BFS or DFS.The current problem is that it is running for infinitely long time.If I let it run for 30 minutes or so.It ends with my RAM getting full.What's the problem in my implementation.I am unsuccessful to debug this code. Thanks in advance.
import copy
import time
import pprint
def get_empty_board():
return [
[7,4,2],
[8,3,0],
[1,5,6]
]
end_state = [
[1,2,3],
[8,0,4],
[7,6,5]
]
def solve_squares(board):
states_explored = list()
states = [ (neighbor,[board] + [neighbor]) for neighbor in get_neighbors(board) ]
while states:
print(len(states))
current_state = states.pop(0)
if (current_state[0]) in states_explored:
continue
# if len(states) > 300:
# states =[ states[0] ]
# pprint.pprint(current_state)
# pprint.pprint(current_state)
if current_state[0] == end_state:
return True,current_state[1]
neighbors = get_neighbors(current_state[0])
states_explored.append(current_state[0])
for neighbor in neighbors:
if (neighbor) not in states_explored:
states.append((neighbor,current_state[1] + [neighbor]))
states_explored.append((neighbor[0]))
return False,None
def get_neighbors(board):
x = None
y = None
neighbors = list()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
x = i
y = j
break
# print(x,y)
for i in range(len(board)):
for j in range(len(board[0])):
if abs(i-x) <= 1 and abs(j-y) <= 1:
if abs(i-x) != abs(j-y):
# print(i,j)
new_state = copy.deepcopy(board)
new_state[x][y] = new_state[i][j]
new_state[i][j] = 0
# pprint.pprint(new_state)
# time.sleep(5)
neighbors.append(new_state)
return neighbors
def main():
result,path = solve_squares(get_empty_board())
print(result)
print(path)
main()