标签:style blog java 2014 os javascript
N皇后问题var N = 4; Array.prototype.count = function(c){ var count = 0; for(var i = 0; i< this.length; i++){if(c(this[i])){count ++;}} return count ; } //init map var arr = new Array(); for(var i = 0 ;i < N;i ++){ var arr1 = new Array(); for(var j = 0;j < N; j++){arr1.push(0);} arr.push(arr1); } var sln = new Array(); var queen = function q(col,done){ //find a vacancy var zeroIndex = 0; while(zeroIndex < N && arr[zeroIndex][col] != 0){zeroIndex ++;} if(zeroIndex < N){ arr[zeroIndex][col] = 1; //update positions updatePosition(zeroIndex,col); done ++; } if(col == N ){return ;} /* debugging console.log("arr : "); for(var i = 0 ;i < arr.length; i++){ console.log (arr[i]); } */ if(done == N-1){ var ar = new Array(); for(var i = 0 ;i < arr.length; i++){ var ar1 = new Array(); for(var j = 0;j < arr[i].length; j++){ ar1.push(arr[i][j]); arr[i][j] = 0; } ar.push(ar1); } sln.push(ar); } col ++; q(col,done); } var updatePosition = function (r,c){ // hor for(var i = 0 ;i < c; i++){if(arr[r][i] == 0) {arr[r][i] = 2;}} for(var i = c ;i < N; i++){if(arr[r][i] == 0) {arr[r][i] = 2;}} //ver for(var i = 0 ;i < r; i++){if(arr[i][c] == 0) {arr[i][c] = 2;}} for(var i = r ;i < N; i++){if(arr[i][c] == 0) {arr[i][c] = 2;}} //r+,c+; r-,c- for(var i = r,j = c;i < N && j < N; i++, j++){if(arr[i][j] == 0){arr[i][j] = 2;}} for(var i = r,j = c;i >=0 && j >= 0; i--, j--){if(arr[i][j] == 0){arr[i][j] = 2;}} //r+,c-;r-,c+ for(var i = r,j = c;i < N && j >= 0; i++, j--){if(arr[i][j] == 0){arr[i][j] = 2;}} for(var i = r,j = c;i >=0 && j < N; i--, j++){if(arr[i][j] == 0){arr[i][j] = 2;}} } for(var i = 0 ;i < N; i++){ arr[i][0] = 1; updatePosition(i,0); queen(1,0); //console.log("================================"); for(var j = 0; j < arr.length; j++){for(var k = 0 ;k <arr[j].length; k++){arr[j][k] = 0;}} } console.log("for " + N + " - " + N + " queen , solutions : ") ; for(var i = 0 ; i< sln.length ;i++){ console.log("=========sln : " + (i+1) + "===================="); for(var j = 0; j < sln[i].length; j++){ console.log(sln[i][j].join(" ")); } }
N皇后问题--回溯法 (循环递归),布布扣,bubuko.com
标签:style blog java 2014 os javascript
原文地址:http://blog.csdn.net/lan_liang/article/details/36005923