def backtrack_forward_mrv(assignment, board, domains,variable_assignment_count):
    variable_assignment_count[0] = variable_assignment_count[0] + 1
    # Tests for completion by adding assignments to board, then restores if not
    # print " -------------------------"
    for i in range(len(assignment)):
        board.CurrentGameboard[assignment[i][0]][assignment[i][1]] = assignment[i][2]
    # board.print_board()
    if sudoku.iscomplete(board.CurrentGameboard):
        return assignment
    for i in range(len(assignment)):
        board.CurrentGameboard[assignment[i][0]][assignment[i][1]] = 0
    # Selects the variable to try values for
    row, col = select_unassigned_variable_mrv(board,assignment, domains)
    # Tries each possible value in the variable's domain
    for val in sudoku.odv_forward(row,col,domains):
        if sudoku.consistent(assignment, row, col, val,board.BoardSize):   # If that value works, adds it to the assignment
            assignment.append([row,col,val])
            domains, changes, possible = sudoku.forward_check(row,col,val,domains,board,assignment) # Also, restricts the domain of other variables
            if possible: # If no conflict is immediately detected, continues to the next variable to be assigned
                result = backtrack_forward_mrv(assignment,board,domains, variable_assignment_count) 
                if result != None: # If that was successful, return its result
                    return result
            if assignment: # Otherwise, remove the assignment and restore the domains
                assignment.pop()
                domains = sudoku.reverse_forward(changes,domains)
    return None # If none of them work, return none
Beispiel #2
0
def backtrack(assignment, board, variable_assignment_count):
	variable_assignment_count[0] = variable_assignment_count[0] + 1
	for i in range(len(assignment)):
		board.CurrentGameboard[assignment[i][0]][assignment[i][1]] = assignment[i][2]    
	if sudoku.iscomplete(board.CurrentGameboard):
		return assignment
	for i in range(len(assignment)):
		board.CurrentGameboard[assignment[i][0]][assignment[i][1]] = 0
	row, col = sudoku.select_unassigned_variable(board,assignment)
	for val in order_domain_values(row, col, assignment, board):
		if sudoku.consistent(assignment, row, col, val,board.BoardSize):
			assignment.append([row,col,val])
			result = backtrack(assignment, board, variable_assignment_count)
			if result != None:
				return result
			if assignment:
				assignment.pop()
	return None