You are on page 1of 38

Recursive (BFS) N-Queens Problem

Design and Analysis of Algorithms


Theory

Submitted by
S.NO NAME REGD.NO ROLL.NO BRANCH SEM

1 AYUSH KUMAR 20010292 CIT20065 CSIT 4TH


2 SATYAM NAYAK 20010241 CIT20012 CSIT 4TH
3 NUTAN RAY 20010264 CIT20037 CSIT 4TH
4 ABHISEK MALLICK 20010247 CIT20019 CSIT 4TH
5 WASIM KHAN 20010248 CIT20020 CSIT 4TH

4th Semester
Computer Science and Information Technology
Department of Computer Science and Engineering
C.V. Raman Global University, Bhubaneswar-752054
ACKNOWLEDGEMENT

We are highly indebted to MR. SANTOSH SHARMA for their


guidance and constant supervision as well as for providing necessary
information regarding the project & also for their support in
completing the project.
We would like to express our gratitude towards our parents &
member of CS&IT for their kind co-operation and encouragement
which help me in completion of this project.
We would like to express our special gratitude and thanks to industry
persons for giving us such attention and time.

<:>
Department of Computer Science and Engineering
C.V. Raman Global University, Bhubaneswar
CERTIFICATE OF APPROVAL

This is to certify that we have examined the project entitled " Recursive (BFS)
N-Queens Problem" submitted by Ayush Kumar (20010292), Nutan Ray
(20010264), Abhisek Mallick (20010247) Wasim Khan (20010248), Satyam
Nayak (20010241) CGU, Bhubaneswar. We here by accord our approval of it as
a major project work carried out and presented in a manner required for its
acceptance for the partial fulfillment for the Bachelor Degree of Technology in
Computer Science & Information Technology for which it has been submitted.
This approval does not necessarily endorse or accept every statement made,
opinion expressed or conclusions drawn as recorded in this major project, it
only signifies the acceptance of the major project for the purpose it has been
submitted.

The Content or matter presented in the thesis have not been submitted anywhere
for award of any other degree.

Signature: AYUSH KUMAR | NUTAN RAY | WASIM KHAN | ABHISEK


MALLICK | SATYAM NAYAK
This is to certify that the above statement is correct to the best of our
knowledge.

Faculty Name: Mr. Santosh Sharma


CONTENTS

o TOPIC INTRODUCTION

o ALGORITHM

o ALGORITHM COMPLEXITY

o PSEUDOCODE

o SOURCE CODE

o OUTPUT

o CONCLUSION
N-Queens Problem
The N–Queens problem is a classic problem that is often used in discussions of
various search strategies. The problem is often defined in terms of a standard
8–by–8 chess board, although it can be defined for any N–by–N board and is
solvable for N ³ 4.
Breadth-first search (BFS) is an algorithm for searching a tree data structure for
a node that satisfies a given property. It starts at the tree root and explores all
nodes at the present depth prior to moving on to the nodes at the next depth
level. Extra memory, usually a queue, is needed to keep track of the child nodes
that were encountered but not yet explored.
For example, in a chess endgame a chess engine may build the game tree from
the current position by applying all possible moves, and use breadth-first search
to find a win position for white. Implicit trees (such as game trees or other
problem-solving trees) may be of infinite size; breadth-first search is guaranteed
to find a solution node[1] if one exists.

The N×N queen’s puzzle is the problem of placing N chess queen on an N×N
chess board so that no two queens attack each other. This approach is a classical
problem in the artificial intelligence area. A solution requires that no two
queens share the same row, column or diagonal. These problems for computer
scientists present practical solution to many useful applications and have
become an important issue. In this paper we proposed new resolution for
solving n-Queens used combination of depth firs search (DFS) and breathe first
search (BFS) techniques. The proposed algorithm act based on placing queens
on chess board directly. This is possible by regular pattern on the basis of the
work law of minister. The results show that performance and run time in this
approach better then back tracking methods and hill climbing modes.

ALGORITHM

Step 1: Create an array for store nodes (UN)


Step 2: Crate an array for store results (BFS_results)
Step 3: Create first node for start
Step 4: Add this node to array UN
Step 5: Create child’s of this nodes
Step 6: Delete this node from array and check for being answer
Step 7: If result is true
7.1 Add this node to results array
7.2 Add this node’s child’s to array(UN)
Step 8: Else
8.1 Delete this node from array
Step 9: Repeat steps 4-8 for start node’s child’s

BFS Time & Space Complexity

The time complexity can be expressed as O(|V|+|E|), since every


vertex and every edge will be explored in the worst case. |V| is the
number of vertices and |E| is the number of edges in the graph. Note
that O(|E|) may vary between O(1) and O(|V|^{2}), depending on how
sparse the input graph is.
When the number of vertices in the graph is known ahead of time, and
additional data structures are used to determine which vertices have
already been added to the queue, the space complexity can be
expressed as O(|V|), where |V| is the number of vertices. This is in
addition to the space required for the graph itself, which may vary
depending on the graph representation used by an implementation of
the algorithm.
When working with graphs that are too large to store explicitly (or
infinite), it is more practical to describe the complexity of breadth-
first search in different terms: to find the nodes that are at distance d
from the start node (measured in number of edge traversals), BFS
takes O(bd + 1) time and memory, where b is the "branching
factor" of the graph (the average out-degree).
PSEUDOCODE (BFS)

Procedure BFS(G, root) is


1 let Q be a queue
2 label root as explored
3 Q.enqueue(root)
4 while Q is not empty do
5 v := Q.dequeue()
6 if v is the goal then
7 return v
8 for all edges from v to w in G.adjacentEdges(v) do
9 if w is not labeled as explored then
10 label w as explored
11 Q.enqueue(w)
SOURCE CODE
Question: Implement an animation for Floyd-Warshall Algorithm
of all pairs shortest path.
 HTML
<!DOCTYPE html>
<html>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<head>
       
        <title>
            Recursive N-Queens
        </title>
       
        <link rel="stylesheet" href="visualizationPageStyle.css">
           
        <link rel="stylesheet" href="ThirdParty/jquery-ui-1.8.11.custom.css">
               
        <script src="ThirdParty/jquery-1.5.2.min.js"></script>
        <script src="ThirdParty/jquery-ui-1.8.11.custom.min.js"></script>
   
        <script type = "text/javascript" src =
"AnimationLibrary/CustomEvents.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/UndoFunctions.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimatedObject.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimatedLabel.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimatedCircle.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimatedRectangle.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimatedLinkedList.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/HighlightCircle.js"> </script>
        <script type = "text/javascript" src = "AnimationLibrary/Line.js">
</script>
        <script type = "text/javascript" src =
"AnimationLibrary/ObjectManager.js"> </script>
        <script type = "text/javascript" src =
"AnimationLibrary/AnimationMain.js"> </script>
        <script type = "text/javascript" src =
"AlgorithmLibrary/Algorithm.js"> </script>
        <script type = "text/javascript" src =
"AlgorithmLibrary/Recursive.js"> </script>
        <script type = "text/javascript" src =
"AlgorithmLibrary/RecQueens.js"> </script>
               
           
     </head>
   
    <body onload="init();" class="VisualizationMainPage">
       
        <div id = "container">
           
            <div id="header">  
                <marquee scrollamount="11" behaviour="scroll"
direction="right"><h1>"Recursive(BFS) N-Queen Problem"</h1></marquee>
            </div>
           
            <div  id = "mainContent">
               
                <div id = "algoControlSection">
                    <table id="AlgorithmSpecificControls"> </table>
                </div>
                                   
                <canvas id="canvas" width="1000" height="500"></canvas>
               
                <div id = "generalAnimationControlSection">

                    <table id="GeneralAnimationControls">  </table>    


                </div>
               
            </div>
           
            <div id="footer">  
                <marquee scrollamount="10" behaviour="scroll"
direction="left"><p>Copyright @ Ayush Kumar | Nutan Ray | Satyam Nayak |
Abhisek Mallick | Wasim Khan</p></marquee>
            </div>

        </div>
    </body>
</html>
 CSS
@charset "utf-8";
body {
    font: 100% Verdana, Arial, Helvetica, sans-serif;
    margin: 0;
    padding: 0;
    text-align: center;
    color: #000000;
}
.VisualizationMainPage #mainContent {

    background: #E1CAB6;
}
.VisualizationMainPage #container {

    background: #FFFFFF;

    text-align: left;
}
.VisualizationMainPage #algoControlSection
{
    background: #301008;
    color:#FFFFFF;
}
.VisualizationMainPage #generalAnimationControlSection
{
    background: #D5BEAB;
    color:#301008;
}
.VisualizationMainPage  #header {
    background: #301008;
    color:#FFFFFF;
    padding: 0 10px 0 20px;
}
.VisualizationMainPage #header  A:visited
      { text-decoration:none;
        color:#ffCC33;
       }
.VisualizationMainPage #header h1 {
    margin: 0;
    padding: 10px 0;
    }
.VisualizationMainPage #header A:link {
    text-decoration:none;
    color:#ffCC33;
    }
.VisualizationMainPage #container {
    background: #FFFFFF;
    margin: 0 auto;
    text-align: left;}  
.VisualizationMainPage #footer  A:visited { text-decoration:none;
        color:ffcc33;
}
.VisualizationMainPage #footer A:link {
    text-decoration:none;
    color:#ffCC33;
}
.VisualizationMainPage #mainContent h1{
    padding: 0 20px;
    background: #FFFFFF;
    color:#006633
}
.VisualizationMainPage #mainContent h2{
    padding: 0 20px;
    background: #FFFFFF;
    color:#006633
}
.VisualizationMainPage #mainContent h3{
    padding: 0 20px;
    background: #FFFFFF;
    color:#006633
}
.VisualizationMainPage #footer {

    padding: 0 15px;
    background: #301008;
    color:#FFFFFF;
    font-size: 20px;
    font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
}
.VisualizationMainPage #footer p {
    margin: 0;  padding: 10px 0;
}
EM {text-decoration: bold;}

 JAVASCRIPT
 Part 1 (N-Queen Algorithm Code)
function Queens(am, w, h)
{
    this.init(am, w, h);
   
}

Queens.prototype = new Recursive();


Queens.prototype.constructor = Queens;
Queens.superclass = Recursive.prototype;

Queens.CALC_QUEENS_ACTIVATION_FIELDS = ["  size  ", "  board  "];


Queens.QUEENS_ACTIVATION_FIELDS = ["  board  ", "  current  ", "  size  ", "
i  ", "  done  "];
Queens.CHECK_ACTIVATION_FIELDS = ["  board  ", "  current  ", "  i  "];

Queens.CODE = [["def ","calcQueens(size)",":"],


                ["     board = ", "[-1] * size"],
                [ "    return  ","queens(board, 0, size)"],
                ["  "],
                ["def ","queens(board, current, size)",":"],
                ["     if ", "(current == size):"],
                ["          return true"],
                ["     else:"],
                ["          for i in range(size):"],
                ["               board[current] = i"],
                ["               if (","noConflicts(board, current)",":"],
                ["                    done"," = ", "queens(board, current +
1, size)"],
                ["                    if (done):"],
                ["                         return true"],
                ["          return false"],
                [" "],
                ["def ","noConflicts(board, current)",":"],
                ["      for i in range(current):"],
                ["         if ","(board[i] == board[current])",":"],
                ["             return false"],
                ["         if ","(current - i == abs(board[current] =
board[i]))",":"],
                ["             return false"],
                ["      return true"]];
               

Queens.RECURSIVE_DELTA_Y_CALC_QUEEN =
Queens.CALC_QUEENS_ACTIVATION_FIELDS.length *
Recursive.ACTIVATION_RECORD_HEIGHT;
Queens.RECURSIVE_DELTA_Y_QUEEN = Queens.QUEENS_ACTIVATION_FIELDS.length *
Recursive.ACTIVATION_RECORD_HEIGHT;
Queens.RECURSIVE_DELTA_Y_CHECK = Queens.CHECK_ACTIVATION_FIELDS.length *
Recursive.ACTIVATION_RECORD_HEIGHT;

Queens.ACTIVATION_RECORT_START_X = 450;
Queens.ACTIVATION_RECORT_START_Y = 20;

Queens.INTERNAL_BOARD_START_X = 600;
Queens.INTERNAL_BOARD_START_Y = 100;
Queens.INTERNAL_BOARD_WIDTH = 20;
Queens.INTERNAL_BOARD_HEIGHT = 20;

Queens.LOGICAL_BOARD_START_X = Queens.INTERNAL_BOARD_START_X;
Queens.LOGICAL_BOARD_START_Y = Queens.INTERNAL_BOARD_START_Y +
Queens.INTERNAL_BOARD_HEIGHT * 1.5;
Queens.LOGICAL_BOARD_WIDTH = Queens.INTERNAL_BOARD_WIDTH;
Queens.LOGICAL_BOARD_HEIGHT = Queens.INTERNAL_BOARD_HEIGHT;
Queens.ACTIVATION_RECORD_SPACING = 400;

Queens.INDEX_COLOR = "#0000FF";

Queens.prototype.init = function(am, w, h)
{
    Queens.superclass.init.call(this, am, w, h);
    this.nextIndex = 0;
    this.addControls();
    this.code = Queens.CODE;
   
   
    this.addCodeToCanvas(this.code);
       
    this.animationManager.StartNewAnimation(this.commands);
    this.animationManager.skipForward();
    this.animationManager.clearHistory();
    this.initialIndex = this.nextIndex;
    this.oldIDs = [];
    this.commands = [];
}

Queens.prototype.addControls =  function()
{
    this.controls = [];
    addLabelToAlgorithmBar("Board size:  (1-8)");

    this.sizeField = addControlToAlgorithmBar("Text", "");


    this.sizeField.onkeydown = this.returnSubmit(this.sizeField,
this.queensCallback.bind(this), 2, true);
    this.controls.push(this.sizeField);

    this.queensButton = addControlToAlgorithmBar("Button", "Queens");


    this.queensButton.onclick = this.queensCallback.bind(this);
    this.controls.push(this.queensButton);
       
}
   

       
Queens.prototype.queensCallback = function(event)
{
    var queensValue;
   
    if (this.sizeField.value != "")
    {
        var queenSize =  parseInt(this.sizeField.value);
        queenSize = Math.min(queenSize, 8);
        this.sizeField.value = String(queenSize);
        this.implementAction(this.doQueens.bind(this),queenSize);
    }
}

Queens.prototype.doQueens = function(size)
{
    this.commands = [];
   
    this.clearOldIDs();
   
   
    this.boardData = new Array(size);
    this.boardInternalID = new Array(size);
    this.boardLogicalID = new Array(size);
    this.boardInternalIndexID = new Array(size);
   
   
    this.currentY = Queens.ACTIVATION_RECORT_START_Y;
    this.currentX = Queens.ACTIVATION_RECORT_START_X;
    this.activationLeft = true;
   
   
    this.cmd("SetForegroundColor", this.codeID[0][1],
Recursive.CODE_HIGHLIGHT_COLOR);
    var activationRec = this.createActivation("calcQueens",
Queens.CALC_QUEENS_ACTIVATION_FIELDS, this.currentX, this.currentY,
this.activationLeft);
    this.currentY += Queens.RECURSIVE_DELTA_Y_CALC_QUEEN;

    this.cmd("SetText", activationRec.fieldIDs[0], size);


    this.cmd("Step");
    this.cmd("SetForegroundColor", this.codeID[0][1],
Recursive.CODE_STANDARD_COLOR);
    this.cmd("SetForegroundColor", this.codeID[1][0],
Recursive.CODE_HIGHLIGHT_COLOR);
    this.cmd("SetForegroundColor", this.codeID[1][1],
Recursive.CODE_HIGHLIGHT_COLOR);
   
   
    for (var i = 0; i < size; i++)
    {
        this.boardInternalID[i] = this.nextIndex++;
        this.oldIDs.push(this.boardInternalID[i])
        this.cmd("CreateRectangle", this.boardInternalID[i],
                 "-1",
                 Queens.INTERNAL_BOARD_WIDTH,
                 Queens.INTERNAL_BOARD_HEIGHT,
                 Queens.INTERNAL_BOARD_START_X  + i *
Queens.INTERNAL_BOARD_WIDTH,
                 Queens.INTERNAL_BOARD_START_Y);

        this.boardInternalIndexID[i] = this.nextIndex++;
        this.oldIDs.push(this.boardInternalIndexID[i]);
        this.cmd("CreateLabel", this.boardInternalIndexID[i],
i,Queens.INTERNAL_BOARD_START_X  + i * Queens.INTERNAL_BOARD_WIDTH,
                 Queens.INTERNAL_BOARD_START_Y -
Queens.INTERNAL_BOARD_HEIGHT);
        this.cmd("SetForegroundColor", this.boardInternalIndexID[i],
Queens.INDEX_COLOR);
       
        this.boardLogicalID[i] = new Array(size);
        for (var j = 0; j < size; j++)
        {
            this.boardLogicalID[i][j] = this.nextIndex++;
            this.oldIDs.push(this.boardLogicalID[i][j]);
           
            this.cmd("CreateRectangle", this.boardLogicalID[i][j],
                     "",
                     Queens.LOGICAL_BOARD_WIDTH,
                     Queens.LOGICAL_BOARD_HEIGHT,
                     Queens.LOGICAL_BOARD_START_X  + j *
Queens.LOGICAL_BOARD_WIDTH,
                     Queens.LOGICAL_BOARD_START_Y  + i *
Queens.LOGICAL_BOARD_HEIGHT);
           
           
        }
    }
    this.cmd("Connect", activationRec.fieldIDs[1], this.boardInternalID[0]);
    this.cmd("Step");
   
    this.cmd("SetForegroundColor", this.codeID[1][0],
Recursive.CODE_STANDARD_COLOR);
    this.cmd("SetForegroundColor", this.codeID[1][1],
Recursive.CODE_STANDARD_COLOR);
    this.cmd("SetForegroundColor", this.codeID[1][1],
Recursive.CODE_STANDARD_COLOR);
    this.cmd("SetForegroundColor", this.codeID[2][1],
Recursive.CODE_HIGHLIGHT_COLOR);
    this.cmd("Step");
    this.cmd("SetForegroundColor", this.codeID[2][1],
Recursive.CODE_STANDARD_COLOR);
   
   
   
   
    board = new Array(size);
    this.queens(board, 0, size);
    this.cmd("Step");
    this.cmd("Delete", this.nextIndex);
    this.deleteActivation(activationRec);

   
    return this.commands;
}

Queens.prototype.queens = function(board, current, size)


{
    var oldX  = this.currentX;
    var oldY = this.currentY;
    var oldLeft = this.activationLeft;
    var activationRec = this.createActivation("queens",
Queens.QUEENS_ACTIVATION_FIELDS, this.currentX, this.currentY,
this.activationLeft);
    this.cmd("SetForegroundColor", this.codeID[4][1],
Recursive.CODE_HIGHLIGHT_COLOR);
   
    this.cmd("SetText", activationRec.fieldIDs[1], current);
    this.cmd("SetText", activationRec.fieldIDs[2], size);
    if (this.activationLeft)
    {
        this.cmd("Connect", activationRec.fieldIDs[0],
this.boardInternalID[0]);
    }
    else
    {      
        this.cmd("Connect", activationRec.fieldIDs[0],
this.boardInternalID[size-1]);      
    }
    this.cmd("Step");
    this.cmd("SetForegroundColor", this.codeID[4][1],
Recursive.CODE_STANDARD_COLOR);
   
    this.cmd("SetForegroundColor", this.codeID[5][1],
Recursive.CODE_HIGHLIGHT_COLOR);
    this.cmd("Step");
    this.cmd("SetForegroundColor", this.codeID[5][1],
Recursive.CODE_STANDARD_COLOR);
   
   
    this.currentY += Queens.RECURSIVE_DELTA_Y_QUEEN;
    if (this.currentY + Queens.RECURSIVE_DELTA_Y_QUEEN > this.canvasHeight)
    {
        this.currentY =  Queens.ACTIVATION_RECORT_START_Y;
        this.currentX += Queens.ACTIVATION_RECORD_SPACING;
        this.activationLeft = false;
    }
   
    if (current == size)
    {
        this.cmd("SetForegroundColor", this.codeID[6][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("SetForegroundColor", this.codeID[6][0],
Recursive.CODE_STANDARD_COLOR);
       
        this.deleteActivation(activationRec);
        this.currentX = oldX;
        this.currentY = oldY;
        this.activationLeft = oldLeft;
        this.cmd("CreateLabel", this.nextIndex, "Return Value = true",
this.currentX, this.currentY);
        this.cmd("SetForegroundColor", this.nextIndex,
Recursive.CODE_HIGHLIGHT_COLOR);

        return true;
    }
   
    var i;
    for (i = 0; i < size; i++)
    {
        this.cmd("SetTextColor", this.codeID[8][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        board[current] = i;
        this.cmd("SetText", activationRec.fieldIDs[3], i);
        this.cmd("Step");
        this.cmd("SetTextColor", this.codeID[8][0],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", this.codeID[9][0],
Recursive.CODE_HIGHLIGHT_COLOR);
       
       
        this.cmd("SetText", this.boardLogicalID[i][current], "Q");
        this.cmd("SetText", this.boardInternalID[current], i);
        this.cmd("Step");
        this.cmd("SetTextColor", this.codeID[9][0],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", this.codeID[10][1],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("SetTextColor", this.codeID[10][1],
Recursive.CODE_STANDARD_COLOR);
       
        var moveLegal = this.legal(board,current);
        this.cmd("SetTextColor", this.codeID[10][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("SetTextColor", this.codeID[10][1],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("Delete",this.nextIndex);
        this.cmd("SetTextColor", this.codeID[10][0],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", this.codeID[10][1],
Recursive.CODE_STANDARD_COLOR);

       
       
       
        if (moveLegal)
        {
            this.cmd("SetTextColor", this.codeID[11][2],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("Step");
            this.cmd("SetTextColor", this.codeID[11][2],
Recursive.CODE_STANDARD_COLOR);
            var done = this.queens(board, current+1, size);
            this.cmd("SetTextColor", this.codeID[11][0],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("SetTextColor", this.codeID[11][1],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("SetTextColor", this.codeID[11][2],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("SetText", activationRec.fieldIDs[4], done);
            this.cmd("Step");
            this.cmd("Delete", this.nextIndex);
            this.cmd("SetTextColor", this.codeID[11][0],
Recursive.CODE_STANDARD_COLOR);
            this.cmd("SetTextColor", this.codeID[11][1],
Recursive.CODE_STANDARD_COLOR);
            this.cmd("SetTextColor", this.codeID[11][2],
Recursive.CODE_STANDARD_COLOR);
            this.cmd("SetTextColor", this.codeID[12][0],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("Step");
            this.cmd("SetTextColor", this.codeID[12][0],
Recursive.CODE_STANDARD_COLOR);
           
            if (done)
            {
                this.cmd("SetTextColor", this.codeID[13][0],
Recursive.CODE_HIGHLIGHT_COLOR);
                this.cmd("Step");
                this.cmd("SetTextColor", this.codeID[13][0],
Recursive.CODE_STANDARD_COLOR);
               
                this.deleteActivation(activationRec);
                this.currentX = oldX;
                this.currentY = oldY;
                this.activationLeft = oldLeft;
                this.cmd("CreateLabel", this.nextIndex, "Return Value = true",
this.currentX, this.currentY);
                this.cmd("SetForegroundColor", this.nextIndex,
Recursive.CODE_HIGHLIGHT_COLOR);

                return true;                        
            }
        }
        this.cmd("SetText", this.boardLogicalID[i][current], "");
       
           
    }
    this.cmd("SetTextColor", this.codeID[14][0],
Recursive.CODE_HIGHLIGHT_COLOR);
    this.cmd("Step");
    this.cmd("SetTextColor", this.codeID[14][0],
Recursive.CODE_STANDARD_COLOR);
    this.deleteActivation(activationRec);
    this.currentX = oldX;
    this.currentY = oldY;
    this.activationLeft = oldLeft;
    this.cmd("CreateLabel", this.nextIndex, "Return Value = false",
this.currentX, this.currentY);
    this.cmd("SetForegroundColor", this.nextIndex,
Recursive.CODE_HIGHLIGHT_COLOR);

    return false;
}

Queens.prototype.legal = function(board, current)


{
    var activationRec = this.createActivation("noConflicts",
Queens.CHECK_ACTIVATION_FIELDS, this.currentX, this.currentY,
this.activationLeft);
    this.cmd("SetText", activationRec.fieldIDs[1], current);
    if (this.activationLeft)
    {
        this.cmd("Connect", activationRec.fieldIDs[0],
this.boardInternalID[0]);
    }
    else
    {      
        this.cmd("Connect", activationRec.fieldIDs[0],
this.boardInternalID[this.boardInternalID.length - 1]);      
    }
    this.cmd("SetForegroundColor", this.codeID[16][1],
Recursive.CODE_HIGHLIGHT_COLOR);
    this.cmd("Step");
    this.cmd("SetForegroundColor", this.codeID[16][1],
Recursive.CODE_STANDARD_COLOR);
   
   
    var i;
    var OK = true;
    if (current == 0)
    {
        this.cmd("SetForegroundColor", this.codeID[17][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step")
        this.cmd("SetForegroundColor", this.codeID[17][0],
Recursive.CODE_STANDARD_COLOR);      
    }
    for (i = 0; i < current; i++)
    {
        this.cmd("SetText", activationRec.fieldIDs[2], i);
        this.cmd("SetTextColor", activationRec.fieldIDs[2],
Recursive.CODE_HIGHLIGHT_COLOR)
        this.cmd("SetForegroundColor", this.codeID[17][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step")
        this.cmd("SetForegroundColor", this.codeID[17][0],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", activationRec.fieldIDs[2],
Recursive.CODE_STANDARD_COLOR)
        this.cmd("SetForegroundColor", this.codeID[18][1],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("SetTextColor", this.boardLogicalID[board[current]][current],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("SetTextColor", this.boardLogicalID[board[i]][i],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("SetTextColor", this.boardLogicalID[board[current]][current],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", this.boardLogicalID[board[i]][i],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetForegroundColor", this.codeID[18][1],
Recursive.CODE_STANDARD_COLOR);

        if (board[i] == board[current])
        {
            this.cmd("SetForegroundColor", this.codeID[19][0],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("Step");
            this.cmd("SetForegroundColor", this.codeID[19][0],
Recursive.CODE_STANDARD_COLOR);
            OK = false;
            break;
        }
        this.cmd("SetTextColor", this.boardLogicalID[board[current]][current],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("SetTextColor", this.boardLogicalID[board[i]][i],
Recursive.CODE_HIGHLIGHT_COLOR);

        this.cmd("SetForegroundColor", this.codeID[20][1],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("SetTextColor", this.boardLogicalID[board[current]][current],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetTextColor", this.boardLogicalID[board[i]][i],
Recursive.CODE_STANDARD_COLOR);
        this.cmd("SetForegroundColor", this.codeID[20][1],
Recursive.CODE_STANDARD_COLOR);
       
        if (current - i == Math.abs(board[current] - board[i]))
        {
            this.cmd("SetForegroundColor", this.codeID[21][0],
Recursive.CODE_HIGHLIGHT_COLOR);
            this.cmd("Step");
            this.cmd("SetForegroundColor", this.codeID[21][0],
Recursive.CODE_STANDARD_COLOR);
           
            OK = false;
            break;
        }
       
    }
    if (OK)
    {
        this.cmd("SetForegroundColor", this.codeID[22][0],
Recursive.CODE_HIGHLIGHT_COLOR);
        this.cmd("Step");
        this.cmd("SetForegroundColor", this.codeID[22][0],
Recursive.CODE_STANDARD_COLOR);
    }
    this.cmd("CreateLabel", this.nextIndex, "Return Value = " + String(OK),
this.currentX, this.currentY);
    this.cmd("SetForegroundColor", this.nextIndex,
Recursive.CODE_HIGHLIGHT_COLOR);
    this.deleteActivation(activationRec);
   
    return OK;
}

var currentAlg;

function init()
{
    var animManag = initCanvas();
    currentAlg = new Queens(animManag, canvas.width, canvas.height);
}
 Part 2 (Recursive)
function Recursive(am, w, h)
{
    if (am != undefined)
        this.init(am, w, h);
   
}
Recursive.prototype = new Algorithm();
Recursive.prototype.constructor = Recursive;
Recursive.superclass = Algorithm.prototype;

Recursive.CODE_START_X = 10;
Recursive.CODE_START_Y = 10;
Recursive.CODE_LINE_HEIGHT = 14;

Recursive.RECURSIVE_START_X = 20;
Recursive.RECURSIVE_START_Y = 120;
Recursive.RECURSIVE_DELTA_Y = 14;
Recursive.RECURSIVE_DELTA_X = 15;
Recursive.CODE_HIGHLIGHT_COLOR = "#FF0000";
Recursive.CODE_STANDARD_COLOR = "#000000";

Recursive.TABLE_INDEX_COLOR = "#0000FF"
Recursive.CODE_RECURSIVE_1_COLOR = "#339933";
Recursive.CODE_RECURSIVE_2_COLOR = "#0099FF";

Recursive.ACTIVATION_RECORD_WIDTH = 100;
Recursive.ACTIVATION_RECORD_HEIGHT = 20;

Recursive.ACTIVATION_RECORD_SPACING = 2 * Recursive.ACTIVATION_RECORD_WIDTH +
10;
Recursive.SEPARATING_LINE_COLOR = "#0000FF"

Recursive.prototype.addCodeToCanvas  = function(code)
{
     this.codeID = this.addCodeToCanvasBase(code, Recursive.CODE_START_X,
Recursive.CODE_START_Y, Recursive.CODE_LINE_HEIGHT,
Recursive.CODE_STANDARD_COLOR);
}
Recursive.prototype.init = function(am, w, h)
{
    Recursive.superclass.init.call(this, am, w, h);
}
Recursive.prototype.clearOldIDs = function()
{
    for (var i = 0; i < this.oldIDs.length; i++)
    {
        this.cmd("Delete", this.oldIDs[i]);
    }
    this.oldIDs =[];
    this.nextIndex = this.initialIndex;
   
}
Recursive.prototype.reset = function()
{
    this.oldIDs =[];
    this.nextIndex = this.initialIndex;
}
Recursive.prototype.enableUI = function(event)
{
    for (var i = 0; i < this.controls.length; i++)
    {
        this.controls[i].disabled = false;
    }
   
   
}
Recursive.prototype.disableUI = function(event)
{
    for (var i = 0; i < this.controls.length; i++)
    {
        this.controls[i].disabled = true;
    }
}
Recursive.prototype.deleteActivation = function(activationRec)

{
    var i;
    for (i = 0; i < activationRec.labelIDs.length; i++)
    {
        this.cmd("Delete", activationRec.labelIDs[i]);
        this.cmd("Delete", activationRec.fieldIDs[i]);
    }
    this.cmd("Delete", activationRec.separatingLineID);
    this.cmd("Delete", activationRec.nameID);
}
Recursive.prototype.createActivation = function(functionName, argList, x, y,
labelsOnLeft)
{
    var activationRec = new ActivationRecord(argList);
    var i;
    activationRec.nameID = this.nextIndex++;
    labelsOnLeft = (labelsOnLeft == undefined) ? true : labelsOnLeft;
    for (i = 0; i < argList.length; i++)
    {
        var valueID = this.nextIndex++;
        activationRec.fieldIDs[i] = valueID;
       
        this.cmd("CreateRectangle", valueID,
                                    "",
                                    Recursive.ACTIVATION_RECORD_WIDTH,
                                    Recursive.ACTIVATION_RECORD_HEIGHT,
                                    x,
                                    y + i *
Recursive.ACTIVATION_RECORD_HEIGHT);
       
        var labelID  = this.nextIndex++;
        activationRec.labelIDs[i] = labelID;
        this.cmd("CreateLabel", labelID, argList[i]);
        if (labelsOnLeft)
            this.cmd("AlignLeft", labelID, valueID);
        else
            this.cmd("AlignRight", labelID, valueID);
    }
    activationRec.separatingLineID = this.nextIndex++;
    this.cmd("CreateLabel", activationRec.nameID, "   " + functionName + "  
");
    this.cmd("SetForegroundColor", activationRec.nameID,
Recursive.SEPARATING_LINE_COLOR);

    if (labelsOnLeft)
    {
        this.cmd("CreateRectangle", activationRec.separatingLineID,
                 "",
                 Recursive.ACTIVATION_RECORD_WIDTH * 2,
                 1,
                 x - Recursive.ACTIVATION_RECORD_WIDTH / 2,
                 y - Recursive.ACTIVATION_RECORD_HEIGHT / 2);
                this.cmd("AlignLeft", activationRec.nameID,
activationRec.labelIDs[0]);
    }
    else
    {
        this.cmd("CreateRectangle", activationRec.separatingLineID,
                 "",
                 Recursive.ACTIVATION_RECORD_WIDTH * 2,
                 1,
                 x + Recursive.ACTIVATION_RECORD_WIDTH / 2,
                 y - Recursive.ACTIVATION_RECORD_HEIGHT / 2);
        this.cmd("AlignRight", activationRec.nameID,
activationRec.labelIDs[0]);

    }
    this.cmd("SetForegroundColor", activationRec.separatingLineID,
Recursive.SEPARATING_LINE_COLOR);
    return activationRec;
   
}
function ActivationRecord(fields){

    this.fields = fields;
    this.values = new Array(this.fields.length);
    var i;
    for (i = 0; i < this.fields.length; i++)
    {
        this.values[i] = "";
    }
    this.fieldIDs = new Array(this.fields.length);
    this.labelIDs = new Array(this.fields.length);  
}
 Part 3 (Algorithm.js)
function addLabelToAlgorithmBar(labelName)
{
    var element = document.createTextNode(labelName);
   
    var tableEntry = document.createElement("td");  
    tableEntry.appendChild(element);
   
   
    var controlBar = document.getElementById("AlgorithmSpecificControls");
   
    //Append the element in page (in span).
    controlBar.appendChild(tableEntry);
    return element;
}
function addCheckboxToAlgorithmBar(boxLabel)
{  
    var element = document.createElement("input");

    element.setAttribute("type", "checkbox");
    element.setAttribute("value", boxLabel);
   
    var label = document.createTextNode(boxLabel);
   
    var tableEntry = document.createElement("td");  
    tableEntry.appendChild(element);
    tableEntry.appendChild(label);
   
    var controlBar = document.getElementById("AlgorithmSpecificControls");
    controlBar.appendChild(tableEntry);
    return element;
}
function addRadioButtonGroupToAlgorithmBar(buttonNames, groupName)
{
    var buttonList = [];
    var newTable = document.createElement("table");
       
    for (var i = 0; i < buttonNames.length; i++)
    {
        var midLevel = document.createElement("tr");
        var bottomLevel = document.createElement("td");
       
        var button = document.createElement("input");
        button.setAttribute("type", "radio");
        button.setAttribute("name", groupName);
        button.setAttribute("value", buttonNames[i]);
        bottomLevel.appendChild(button);
        midLevel.appendChild(bottomLevel);
        var txtNode = document.createTextNode(" " + buttonNames[i]);
        bottomLevel.appendChild(txtNode);
        newTable.appendChild(midLevel);
        buttonList.push(button);
    }
   
    var topLevelTableEntry = document.createElement("td");
    topLevelTableEntry.appendChild(newTable);
   
    var controlBar = document.getElementById("AlgorithmSpecificControls");
    controlBar.appendChild(topLevelTableEntry);
   
    return buttonList
}
function addControlToAlgorithmBar(type, name) {
    var element = document.createElement("input");
    element.setAttribute("type", type);
    element.setAttribute("value", name);
    var tableEntry = document.createElement("td");
    tableEntry.appendChild(element);
    var controlBar = document.getElementById("AlgorithmSpecificControls");
    controlBar.appendChild(tableEntry);
    return element;
   
}
function Algorithm(am)
{}
Algorithm.prototype.setCodeAlpha = function(code, newAlpha)
{
   var i,j;
   for (i = 0; i < code.length; i++)
       for (j = 0; j < code[i].length; j++) {
          this.cmd("SetAlpha", code[i][j], newAlpha);
       }
}
Algorithm.prototype.addCodeToCanvasBase  = function(code, start_x, start_y,
line_height, standard_color, layer)
{
        layer = typeof layer !== 'undefined' ? layer : 0;
    var codeID = Array(code.length);
    var i, j;
    for (i = 0; i < code.length; i++)
    {
        codeID[i] = new Array(code[i].length);
        for (j = 0; j < code[i].length; j++)
        {
            codeID[i][j] = this.nextIndex++;
            this.cmd("CreateLabel", codeID[i][j], code[i][j], start_x, start_y
+ i * line_height, 0);
            this.cmd("SetForegroundColor", codeID[i][j], standard_color);
            this.cmd("SetLayer", codeID[i][j], layer);
            if (j > 0)
            {
                this.cmd("AlignRight", codeID[i][j], codeID[i][j-1]);
            }
        }
       
       
    }
    return codeID;
}
Algorithm.prototype.init = function(am, w, h)
{
    this.animationManager = am;
    am.addListener("AnimationStarted", this, this.disableUI);
    am.addListener("AnimationEnded", this, this.enableUI);
    am.addListener("AnimationUndo", this, this.undo);
    this.canvasWidth = w;
    this.canvasHeight = h;
   
    this.actionHistory = [];
    this.recordAnimation = true;
    this.commands = []
}
Algorithm.prototype.sizeChanged = function(newWidth, newHeight)
{
   
}
Algorithm.prototype.implementAction = function(funct, val)
{
    var nxt = [funct, val];        
    this.actionHistory.push(nxt);
    var retVal = funct(val);
    this.animationManager.StartNewAnimation(retVal);            
}
       
       
Algorithm.prototype.isAllDigits = function(str)
{
    for (var i = str.length - 1; i >= 0; i--)
    {
        if (str.charAt(i) < "0" || str.charAt(i) > "9")
        {
            return false;

        }
    }
    return true;
}
       
       
Algorithm.prototype.normalizeNumber = function(input, maxLen)
{
    if (!this.isAllDigits(input) || input == "")
    {
        return input;
    }
    else
    {
        return ("OOO0000" +input).substr(-maxLen, maxLen);
    }
}
       
Algorithm.prototype.disableUI = function(event) {
}

Algorithm.prototype.enableUI = function(event) {
}

function controlKey(keyASCII)
{
        return keyASCII == 8 || keyASCII == 9 || keyASCII == 37 || keyASCII ==
38 ||
    keyASCII == 39 || keyASCII == 40 || keyASCII == 46;
}

Algorithm.prototype.returnSubmitFloat = function(field, funct, maxsize)


{
    if (maxsize != undefined)
    {
        field.size = maxsize;
    }
    return function(event)
    {
        var keyASCII = 0;
        if(window.event) // IE
        {
            keyASCII = event.keyCode
        }
        else if (event.which)
        {
            keyASCII = event.which
        }
        if (keyASCII == 13)
        {
            funct();
        }
        else if (controlKey(keyASCII))
        {
            return;
        }
        else if (keyASCII == 109)
        {
            return;
        }
        else if ((maxsize != undefined || field.value.length < maxsize) &&
                 (keyASCII >= 48 && keyASCII <= 57))
        {
            return;
        }
        else if ((maxsize != undefined || field.value.length < maxsize) &&
                 (keyASCII == 190) && field.value.indexOf(".") == -1)
                 
        {
            return;
        }
        else        
        {
            return false;
        }
       
    }
}
Algorithm.prototype.returnSubmit = function(field, funct, maxsize, intOnly)
{
    if (maxsize != undefined)
    {
        field.size = maxsize;
    }
    return function(event)
    {
        var keyASCII = 0;
        if(window.event)
        {
            keyASCII = event.keyCode
        }
        else if (event.which)
        {
            keyASCII = event.which
        }

        if (keyASCII == 13 && funct !== null)


        {
            funct();
        }
                else if (keyASCII == 190 || keyASCII == 59 || keyASCII == 173
|| keyASCII == 189)
        {
            return false;  
           
        }
        else if ((maxsize != undefined && field.value.length >= maxsize) ||
                 intOnly && (keyASCII < 48 || keyASCII > 57))
        {
            if (!controlKey(keyASCII))
                return false;
        }
       
    }
   
}

Algorithm.prototype.addReturnSubmit = function(field, action)


{
    field.onkeydown = this.returnSubmit(field, action, 4, false);  
}

Algorithm.prototype.reset = function() {
}
       
Algorithm.prototype.undo = function(event)
{
   
    this.actionHistory.pop();
   
    this.reset();
   
    var len = this.actionHistory.length;
    this.recordAnimation = false;
    for (var i = 0; i < len; i++)
    {
        this.actionHistory[i][0](this.actionHistory[i][1]);
    }
    this.recordAnimation = true;
}

Algorithm.prototype.clearHistory = function()
{
    this.actionHistory = [];
}

Algorithm.prototype.cmd = function()
{
    if (this.recordAnimation)
    {
        var command = arguments[0];
        for(i = 1; i < arguments.length; i++)
        {
            command = command + "<;>" + String(arguments[i]);
        }
        this.commands.push(command);
    }
   
}

OUTPUTS
 1st Screenshot

 2nd Screenshot

 3rd Screenshot
 4th Screenshot
CONCLUSION

In this work, we proposed recursive BFS algorithm for solving n-


queen problems. The proposed algorithm act based on placing queens
on chess board directly. The results show that performance and run
time in this approach better then back tracking methods and hill
climbing modes. As a result, the DFS algorithm is quicker than BFS
algorithm and Number of extended node in DFS algorithm is less than
BFS algorithm as well as the required memory for BFS is larger than
DFS. Using this method, time and cost of solving n-queens problem is
minimized in comparison of old methods. As future work, we can also
find more efficient algorithms to solving n-queen problem based on
other AI techniques.
THANK YOU

THE END
\<.>/

You might also like