I am learning recursion coding, and I tried a test for myself- the 8-queen puzzle. I check if there is conflict at each step, and backtrack if there is a conflict. But it seems that my code stops backtracking prematurely.
First, I have:
0000
0000
0000
0000
then it changes to:
1000
0000
0000
0000
and then it changes to:
1100
0000
0000
0000
Now the conflict function returns True, and the function stops.
Why isn't it calling solve_queen(grid)
with:
1010
0000
0000
0000
I think there is something wrong with the two for
loops in solve_queen(grid)
but I can't get exactly where it went wrong.
My code follows.
import copy
q4_zero = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
def format_failed(grid):
if len(grid) != len(grid[0]):
return True
elif len(grid) < 4:
return True
return False
def row_conflict(grid):
for row in grid:
if row.count(1) > 1:
return True
return False
def col_conflict(grid):
new_grid = [[r[col] for r in grid] for col in range(len(grid[0]))]
return row_conflict(grid)
def oblique_conflict(grid):
i_lst = []
j_lst = []
row_count = len(grid)
for i in xrange(row_count):
if grid[i].count(1) > 0:
j = grid[i].index(1)
i_lst.append(i)
j_lst.append(j)
for k in xrange(len(i_lst)):
for m in xrange(len(i_lst) - 1):
if abs(i_lst[m] - i_lst[m + 1]) == abs(j_lst[m] - j_lst[m + 1]):
return True
return False
def conflict(grid):
if format_failed(grid):
return True
elif row_conflict(grid):
return True
elif col_conflict(grid):
return True
elif oblique_conflict(grid):
return True
return False
def solve_queen(__grid):
res = conflict(__grid)
if res is True:
return res
grid = copy.deepcopy(__grid)
N = len(grid)
for i in xrange(N):
for j in xrange(N):
if grid[i][j] == 0:
grid[i][j] = 1
final_answer = solve_queen(grid)
if final_answer is not True:
return final_answer
return True
return grid
print solve_queen(q4_zero)