Subscribe Us

Responsive Advertisement

Advertisement

Write programs to solve N-Queens problem using the following algorithms Using a. Steepest Ascent Hill Climbing | Python code

 import random

import math
def printans(state):
    n=len(state)
    for row in range(n):
        li=""
        for col in range(n):
            if state[col]==row:
                li=li+"Q "
            else:
                li=li+". "
        print(li)

           
def get_random(n):
    return [random.randint(0,n-1) for x in range(n)]

def get_adjacent(cur):
    neighbore=[]
    n=len(cur)
    for col in range(n):
        for row in range(n):
            if cur[col]!=row:
                nb=list(cur)
                nb[col]=row
                neighbore.append(nb)
    return neighbore

def conflict(state):
    ans=0
    n=len(state)
    for i in range(n):
        for j in range(i+1,n):
            if state[i]==state[j] or abs(state[i]-state[j])==abs(i-j):
                ans=ans+1
    return ans

def sahc(n):
    cur=get_random(n)
    while True:
        adjacent=get_adjacent(cur)
        next_state=min(adjacent,key=conflict)
        if conflict(next_state)>=conflict(cur):
            return cur
        cur=next_state




   
ans=sahc(8)
print("sahc : ")
printans(ans)

Post a Comment

0 Comments