Inhalt | Code | Beispiel |
C | Javascript | Kommentare | Zeilennummern | Midnight |
/**
* 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 = 0; row_count < cols; row_count++ ) {
document.write("<tr>");
for ( var col_count = 0; col_count < cols; col_count++ ) {
document.write("<td");
if ( !col_count )
document.write(" height='40px'");
if ( (row_count + col_count) %2 != 0 )
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 + ")'> </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 (col, row) {
for ( var i = 0; i < col; i++ ) {
if ( i == col || filled_columns[i] < 0 )
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 i = 0; i < cols; i++ ) {
if ( col == given_col && i != filled_columns[given_col] )
continue;
tries_to_set++;
if ( !is_possible(col, i) )
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 i, field;
for ( i = 0; i < cols; i++ ) {
if ( filled_columns[i] < 0 )
continue;
field = filled_columns[i] * cols + i;
iD("cell_" + field).innerHTML = "Q";
}
for ( i = 0; i < (cols * cols); i++ )
iD("cell_" + i).style.cursor = "default";
var the_tries = (tries_to_set > 999) ? tries_to_set : " " + tries_to_set;
debug( "*******************************************" );
debug( "* First found solution, " + the_tries + " tries needed *" );
debug( "*******************************************" );
}
function set_given_queen (row, col) {
if ( given_col >= 0 )
return;
given_col = col;
filled_columns[col] = row;
for ( var i = 0; i < (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 ( i = 0; i < cols; i++ )
filled_columns[i] = -1;