递归(Recursion)
迷宫是否有解问题
class Map{
constructor(width,height) {
this.width=width;
this.height=height;
this.map=new Array(height);
for(let i=0;i<height;i++){
this.map[i] = new Array(width);
this.map[i][0]=1;//第一列为墙
this.map[i][width-1]=1;
}
for(let i=0; i<width;i++){
this.map[0][i]=1;
this.map[height-1][i]=1;
}
for(let i= 0;i<this.height;i++){
for(let j=0;j<this.width;j++){
if(this.map[i][j]==undefined){
this.map[i][j]=0;
}
}
}
this.map[3][2]=1;
this.map[3][1]=1
}
show(){
document.write("<br />")
for(let i= 0;i<this.height;i++){
for(let j=0;j<this.width;j++){
document.write(this.map[i][j]);
}
document.write("<br />")
}
}
setWay(i,j){//下->右->上->左 1表示墙2表示可以走3表示可以走但走不通
// console.log("递归")
if(this.map[this.height-2][this.width-2]==2){//走到了终点
return true;
}else{
if(this.map[i][j]==0){//还没走
this.map[i][j]=2;//假定可以走通
if(this.setWay(i+1,j)){//向下走
return true;
}else if(this.setWay(i,j+1)){//向右走
return true;
}else if(this.setWay(i-1,j)){//向上走
return true;
}else if(this.setWay(i,j-1)){//向左走
return true;
}else{
this.map[i][j]=3;//该点走不通
return false;
}
}else{//已经走过了
return false;
}
}
}
}
var map = new Map(7,7);
map.show()
map.setWay(1,1);//从左上角走到右下角
map.show()
递归解决八皇后问题
var positions = new Array(8);//创建一个数组保存每一行皇后的列
var count =0;
check(0);
console.log(count)
function show(){
for(let i=0;i<8;i++){
document.write(positions[i]+" ");
}
document.write("<br /> ");
}
function judge(n){
for(let i=0;i<n;i++){
if(positions[i]==positions[n]||Math.abs(n-i)==Math.abs(positions[n]-positions[i])){//在同一列或斜线上
return false;
}
}
return true;
}
function check(n){
if(n==8){
show();
count++;
return;
}
for(let i=0;i<8;i++){
positions[n]=i;
if(judge(n)){//不冲突
check(n+1);//接着放下一个皇后
}else{
continue;
}
}
}