Inhalt | Code | Beispiel |
C | Javascript | Kommentare | Zeilennummern | Midnight |
001 // Author Malte Pagel
002
003 var cols = 8;
004
005 document.write("<center><table border='1'>");
006 for ( var row_count = 0; row_count < cols; row_count++ ) {
007 document.write("<tr>");
008 for ( var col_count = 0; col_count < cols; col_count++ ) {
009 document.write("<td");
010 if ( !col_count )
011 document.write(" height='40px'");
012 if ( (row_count + col_count) %2 != 0 )
013 document.write(" class='dark_cell'");
014 document.write(">");
015 document.write("<div id='cell_" + (row_count * cols + col_count)
016 + "' class='table_cell' onclick='set_given_queen(" + row_count + ", " + col_count + ")'> </div>");
017 document.write("</td>");
018 }
019 document.write("</tr>");
020 }
021 document.write("</table></center>");
022
023 var filled_columns = [];
024 var given_col = -1;
025 var tries_to_set = 0;
026 var i;
027
028
029 function is_possible (col, row) {
030 for ( var i = 0; i < col; i++ ) {
031 if ( i == col || filled_columns[i] < 0 )
032 continue;
033
034 if ( filled_columns[i] == row )
035 return 0;
036
037 if ( Math.abs(row - filled_columns[i]) == Math.abs(col - i) )
038 return;
039 }
040
041 return 1;
042 }
043
044 function recursive_queen_search (col) {
045
046 for ( var i = 0; i < cols; i++ ) {
047 if ( col == given_col && i != filled_columns[given_col] )
048 continue;
049
050 tries_to_set++;
051
052 if ( !is_possible(col, i) )
053 continue;
054
055 filled_columns[col] = i;
056
057 if ( col == (cols - 1) || recursive_queen_search(col + 1) )
058 return 1;
059 }
060
061 if ( col != given_col )
062 filled_columns[col] = -1;
063 return 0;
064 }
065
066 function show_queens () {
067 var i, field;
068 for ( i = 0; i < cols; i++ ) {
069 if ( filled_columns[i] < 0 )
070 continue;
071 field = filled_columns[i] * cols + i;
072 iD("cell_" + field).innerHTML = "Q";
073 }
074
075 for ( i = 0; i < (cols * cols); i++ )
076 iD("cell_" + i).style.cursor = "default";
077
078 var the_tries = (tries_to_set > 999) ? tries_to_set : " " + tries_to_set;
079
080 debug( "*******************************************" );
081 debug( "* First found solution, " + the_tries + " tries needed *" );
082 debug( "*******************************************" );
083 }
084
085 function set_given_queen (row, col) {
086 if ( given_col >= 0 )
087 return;
088
089 given_col = col;
090 filled_columns[col] = row;
091
092 for ( var i = 0; i < (cols * cols); i++ )
093 iD("cell_" + i).style.cursor = "wait";
094
095 iD("cell_" + (row * cols + col)).parentNode.style.border = "thin solid #FF8000";
096
097 iD("instruction").innerHTML = "";
098
099 if ( recursive_queen_search(0) )
100 show_queens();
101 else {
102 debug( "**********************************" );
103 debug( "* Could not find solution, sorry *" );
104 debug( "**********************************" );
105 }
106 }
107
108 for ( i = 0; i < cols; i++ )
109 filled_columns[i] = -1;
110