N Queens?

I was trying to solve the Standard N Queens problem and came up with this Code, it's in Python maybe I'll do this is C++ too, but really with that cryptic syntax of vectors, it looks really tougher to understand code compared to the ones written in Python although there isn't much difference that would arise if we remove those vector syntax. Well, I am working on 1 more problem that I have been trying to solve for the last 3 days, and today came with one idea that passed all the sample Test Cases but the irony is that when it came to other Test Cases, it failed badly and now I can't figure out what bug is there in my code, cause it's a fairly long code and also there is not surety of whether the logic that I am using is correct or not.


For the below syntax I think that the code should be sufficient and also not to mention that this problem is very much related to the DFS traversing technique of Graphs where it was Vertices that we were traversing through but here we have Chess Board Positions, the idea is same, here also the function calls are being used a built in stack. And after every conclusion that is not final we move on to the next option by backtracking to the previous choices and continue with the options untill we run out of choices and eventually return False as the result. For no result also I am printing the Board.

And I have kept print statements to describe and give a better understanding of the state of the Program and how the backtracking is working, you just have to imagine the Chess Board( just a 2D Matrix ) and you will get the Problem.

# =============================================================================
# ''' Code For The Standard N-Queens Problem '''
# =============================================================================

def isSafe(board,row,col):
    ''' To check if this row is Safe for the Queen or not '''
    it1=row
    it2=col
    # Checking the left part of the current row
    for i in range(col-1,-1,-1):
        if(board[row][i]==1):
            return False
    # Now checking the upper diagonal in the left direction
    while(it1>=0 and it2>=0):
        if(board[it1][it2]==1):
            return False
        it1-=1
        it2-=1
    it1=row
    it2=col
    # Checking for the Lower Diagonal in the left direction
    while(it1<len(board) and it2>=0):
        if(board[it1][it2]==1):
            return False
        it1+=1
        it2-=1
    # Otherwise just return True, means this position is safe
    return True

def nQueens(board,cols):
    # Base Condition
    # print("Here")
    if(cols>=len(board)):
        return True
       
    rows=len(board)
    for i in range(rows):
        # print("Here??")
        if(isSafe(board,i,cols)):
            print(f"For column {cols}, safe row is {i}")
            board[i][cols]=1
            if(nQueens(board,cols+1)==True):
                return True
       
        # Else change the current position back to 0
        board[i][cols]=0
    print(f"There was no valid option for the column: {cols}, so Backtracking... ")
    return False  

cols=int(input("Dimensions? "))

def main():
    board=[[0 for i in range(cols)] for j in range(cols)]
   
    print(f"Was there a Valid Answer? {nQueens(board,0)}")
    # print("Are we here?")
    # Print the Board
    for i in range(cols):
        for j in range(cols):
            print(board[i][j],end=" ")
        print()
if __name__=="__main__":
    main()

Comments

Popular Posts