递归::骑士问题

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd“>
<html>
 <head>
  <meta http-equiv=”Content-Type” content=”text/html; charset=gbk” />
  <title>Untitled Document</title>
 </head>
 <body>
  <p>骑士问题</p>
  <p>在一个N*N的棋盘上,给骑士一个起点(X,Y),骑士必须以这个起点开始,
  走完所有的棋盘上的每个点,走法相当于中国象棋“马”的走法</p>
  <p>与迷宫问题相同,在任何一个起点,该骑士有八个方向可走,终止的条件是该骑士已经走过了N*N个步。</p>
  <p>由于N=5时有几百个解,所以让firefox“停止脚本”</p>
  <script type=”text/javascript”>
   function isRange(next_x,next_y){
    return next_x>=0 && next_x<N && next_y>=0 && next_y<N;
   }
   function showResult(){
    document.writeln(“<table border=’1′”);
    for(var i=0;i<N;i++){
     document.writeln(“<tr>”);
     for(var j=0;j<N;j++){
      document.writeln(“<td>”+mazing[i][j]+”</td>”);
     }
     document.writeln(“</tr>”);
    }
    document.writeln(“</table>”)
   }
   function tour(counter,x,y){
    var next_x,next_y;
    for(var i=0,cnt=direct.length;i<cnt;i++){
     next_x=x+direct[i][0];
     next_y=y+direct[i][1];
     if(isRange(next_x,next_y)){
      if(mazing[next_x][next_y]==0){
       mazing[next_x][next_y]=counter+1;
       if(counter==N*N-1){
        showResult();
       }else{        
        tour(counter+1,next_x,next_y)
       }
       mazing[next_x][next_y]=0;
      }
     }
    }
   }
   
   var i=0,direct=[],N=5;
   direct[i++]=[1,2];
   direct[i++]=[2,1];
   direct[i++]=[2,-1];
   direct[i++]=[1,-2];
   direct[i++]=[-1,-2];
   direct[i++]=[-2,-1];
   direct[i++]=[-2,1];
   direct[i++]=[-1,2];
   var mazing=[];
   for(i=0;i<N;i++){
    mazing[i]=[];
    for(var j=0;j<N;j++){
     mazing[i][j]=0;
    }
   }
   
   var MAXSTEP=N*N;
   mazing[0][0]=1;
   tour(1,0,0);
  </script>
 </body>
</html>

 

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/beimuaihui/article/details/2111938
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞