用js递归了个算法:
// queenNum 为皇后个数, showResult为function(arr){}函数指针 function queen(queenNum, showResult){ var arr = (function(){ var arr = new Array(queenNum); for(var i=0; i<arr.length; i++){ arr[i] = 0; } return arr; })(); var isSafe = function(colIndex, rowValue){ for(var i = 0; i<colIndex; i++){ if(arr[i] == rowValue || colIndex - i == rowValue - arr[i] || colIndex - i == arr[i] - rowValue){ return false; } } return true; }; var placeQueen = function(colIndex){ var rowValue = 0; while(rowValue < arr.length){ if(isSafe(colIndex, rowValue)){ arr[colIndex] = rowValue; if(colIndex == arr.length - 1){ showResult(arr); }else{ placeQueen(colIndex + 1); } } rowValue++; } }; placeQueen(0); };
参考:
http://www.cnblogs.com/jillzhang/archive/2007/10/21/922830.html
http://blog.csdn.net/hackbuteer1/article/details/6657109