Wednesday, February 26, 2014

Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

__author__ = 'nitin'

def print_queens():
    print "Result Queen Board:",column_for_row

def place_queen(row):
    if row==8:
        print_queens()
        return True
    for i in range(8):
        column_for_row[row]=i
        if check(row):
            done=place_queen(row+1)
            if done:
                return True

def check(row):
    for i in range(row):
        diff=abs(column_for_row[i] - column_for_row[row])
        if diff ==0 or diff == row -i:
            return False
    return True

if __name__=='__main__':
    column_for_row=[-1]*8
    place_queen(0)

No comments:

My Profile

My photo
can be reached at 09916017317