Friday 27 October 2017

8 Queens using BackTracking in Python using JSON file as Input

Input

The input to the program is the position of the first queen which taken from a json file.




Code

import json

def safe(row,col,board):
 for i in range(row):
  if board[i][col]==1:
   return False

 i=row-1
 j=col-1

 while i>=0 and j>=0:
  if board[i][j]==1:
   return False
  i-=1
  j-=1
 
 i=row-1
 j=col+1

 while i>=0 and j<=7:
  if board[i][j]==1:
   return False
  i-=1
  j+=1

 return True


def solve(board,row):
 col=0
 if row==8:
  return True
 while col<=7:
  if safe(row,col,board):
   board[row][col]=1
   if solve(board,row+1):
    return True
   else:
    board[row][col]=0


  col+=1
 return False


def pboard(board):
 for i in range(8):
  for j in range(8):
   print board[i][j],
  print
  
with open('input.json') as f:
 data=json.load(f)
board=[[0 for x in range (8)] for y in range (8)]
board[0][int(data["start"])]=1


if(solve(board,1)):
 print "Solved"
 pboard(board) 
else:
 print "Failed to Solve"

input.json

{"start":0}

Output

[duke@duke-pc b1]$ python2 q.py
Solved
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0

5 comments:


  1. I appreciate this piece of useful information. Kshemkari Export Import academy one of the best leading Trade and Training Institute for import and export business, provides the best service in India with expert TeamFor more information visit our site: Export Import Certificate Online Training

    ReplyDelete
  2. virtual event platform Zoom Video Communications experienced massive growth last year (its fiscal year 2021) throughout the pandemic, which decimated thousands of other businesses. which of the following would be the most effective opening for a thank-you note?, virtual gift bags, free event registration platforms, workshop invitation email and email invite examples

    ReplyDelete