/**
 * Author Malte Pagel
 * Free to use for any purpose
 * Runability or usefulness is NOT guaranteed
 */


var cols 8;
                
document.write("<center><table border='1'>");
for ( var 
row_count 0row_count colsrow_count++ ) {
    
document.write("<tr>");
    for ( var 
col_count 0col_count colscol_count++ ) {
        
document.write("<td");
        if ( !
col_count )
            
document.write(" height='40px'");
        if ( (
row_count col_count) %!= )
            
document.write(" class='dark_cell'");
        
document.write(">");
        
document.write("<div id='cell_" + (row_count cols col_count)
            + 
"' class='table_cell' onclick='set_given_queen(" row_count ", " col_count ")'>&nbsp;</div>");
        
document.write("</td>");
    }
    
document.write("</tr>");
}
document.write("</table></center>");

var 
filled_columns = [];
var 
given_col = -1;
var 
tries_to_set 0;
var 
i;


function 
is_possible (colrow) {                    
    for ( var 
0coli++ ) {
        if ( 
== col || filled_columns[i] < )
            continue;

        if ( 
filled_columns[i] == row )
            return 
0;

        if ( 
Math.abs(row filled_columns[i]) == Math.abs(col i) )
            return;
    }

    return 
1;
}

function 
recursive_queen_search (col) {

    for ( var 
0colsi++ ) {
        if ( 
col == given_col && != filled_columns[given_col] )
            continue;

        
tries_to_set++;

        if ( !
is_possible(coli) )
            continue;

        
filled_columns[col] = i;

        if ( 
col == (cols 1) || recursive_queen_search(col 1) )
            return 
1;
    }

    if ( 
col != given_col )
        
filled_columns[col] = -1;
    return 
0;
}

function 
show_queens () {
    var 
ifield;
    for ( 
0colsi++ ) {
        if ( 
filled_columns[i] < )
            continue;
        
field filled_columns[i] * cols i;
        
iD("cell_" field).innerHTML "Q";
    }

    for ( 
0< (cols cols); i++ )
        
iD("cell_" i).style.cursor "default";

    var 
the_tries = (tries_to_set 999) ? tries_to_set "&nbsp;" tries_to_set;

    
debug"*******************************************" );
    
debug"* First found solution, " the_tries " tries needed *" );
    
debug"*******************************************" );
}

function 
set_given_queen (rowcol) {
    if ( 
given_col >= )
        return;

    
given_col col;
    
filled_columns[col] = row;

    for ( var 
0< (cols cols); i++ )
        
iD("cell_" i).style.cursor "wait";

    
iD("cell_" + (row cols col)).parentNode.style.border "thin solid #FF8000";

    
iD("instruction").innerHTML "";

    if ( 
recursive_queen_search(0) )
        
show_queens();
    else {
        
debug"**********************************" );
        
debug"* Could not find solution, sorry *" );
        
debug"**********************************" );
    }
}

for ( 
0colsi++ )
    
filled_columns[i] = -1;