• 算法分析之马走日字


    国际象棋的棋盘为8*8的方格棋盘。现将"马"放在任意指定的方格中,按照"马"走棋的规则将"马"进行移动。要求每个方格只能进入一次,最终使得"马"走遍棋盘的64个方格。编写一个C程序,实现马踏棋盘操作,要求用1~64这64个数字标注马移动的路径,也就是按照求出的行走路线,将数字1,2,……64依次填入棋盘的方格中,并输出。
     解决马踏棋盘问题的一种比较容易理解的方法是应用递归的深度优先搜索的思想。
      

     1 /*
     2  * ChessHorse.h
     3  *
     4  *  Created on: 2016年2月24日
     5  *      Author: hoojjack
     6  */
     7 
     8 #pragma once
     9 #include <stdio.h>
    10 #include <stdlib.h>
    11 #include <time.h>
    12 #include <windows.h>
    13 namespace section10_horseMove{
    14 typedef struct {
    15     int x;
    16     int y;
    17 }Coordinate;
    18 int chessBoard[8][8];
    19 int curstep;
    20 Coordinate direction[8]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
    21 void outPut(int (*chess)[8]){
    22     for(int i=0;i<8;i++){
    23         for(int j=0;j<8;j++){
    24             printf("%d	",chess[i][j]);
    25         }
    26         printf("
    ");
    27     }
    28 }
    29 /*
    30  * 按照一条路先一直往下走,如果没有合适的路就按原路返回,同时恢复现场,这样直到将所有的路径都试到
    31  */
    32 void horseMove(Coordinate temp){
    33     Coordinate next;
    34     if(temp.x<0||temp.x>7||temp.y<0||temp.y>7){
    35         return ;
    36     }
    37     if(chessBoard[temp.x][temp.y]){
    38         return;
    39     }
    40     chessBoard[temp.x][temp.y]=curstep;
    41     curstep++;
    42     if(curstep>64){
    43         outPut(chessBoard);
    44         exit(0);
    45     }else{
    46         for(int i=0;i<8;i++){
    47             next.x=temp.x+direction[i].x;
    48             next.y=temp.y+direction[i].y;
    49             if(next.x<0||next.x>7||next.y<0||next.y>7){
    50                 continue;
    51             }else{
    52                 horseMove(next);
    53             }
    54         }
    55     }
    56     //outPut(chessBoard);
    57     //Sleep(100);
    58     chessBoard[temp.x][temp.y]=0;
    59     //outPut(chessBoard);
    60     curstep--;
    61     //Sleep(100);
    62 //    printf("A barrier!
     ");
    63 }
    64 
    65 void runHorseMove(){
    66     Coordinate start;
    67     printf("Please input the first location of the horse!
    ");
    68     scanf("%d%d",&start.x,&start.y);
    69     if(start.x<0||start.x>7||start.y<0||start.y>7){
    70         printf("The location is error");
    71         exit(0);
    72     }
    73     for(int i=0;i<8;i++){
    74         for(int j=0;j<8;j++){
    75             chessBoard[i][j]=0;
    76         }
    77     }
    78     curstep=1;
    79     horseMove(start);
    80 }
    81 
    82 }
  • 相关阅读:
    经典的阿里前端笔试题
    Javascript之浏览器兼容EventUtil
    Javascript之对象的创建
    奇妙的CSS之CSS3新特性总结
    前端优化之无阻塞加载脚本
    正则表达式规则与常见的正则表达式
    全端工程师
    最全前端面试问题及答案总结--《转载》
    奇妙的CSS之布局与定位
    关于在django框架里取已登录用户名字的问题
  • 原文地址:https://www.cnblogs.com/hoojjack/p/5215197.html
Copyright © 2020-2023  润新知