欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

DFS(二):骑士游历问题

程序员文章站 2022-03-20 17:13:24
在国际象棋的棋盘(8行×8列)上放置一个马,按照“马走日字”的规则,马要遍历棋盘,即到达棋盘上的每一格,并且每格只到达一次。例如,下图给出了骑士从坐标(1,5)出发,游历棋盘的一种可能情况。 【例1】骑士游历问题。 编写一个程序,对于给定的起始位置(x0,y0),探索出一条路径,沿着这条路径骑士能遍 ......

      在国际象棋的棋盘(8行×8列)上放置一个马,按照马走日字的规则,马要遍历棋盘,即到达棋盘上的每一格,并且每格只到达一次。例如,下图给出了骑士从坐标(1,5)出发,游历棋盘的一种可能情况。

DFS(二):骑士游历问题

【例1】骑士游历问题。

       编写一个程序,对于给定的起始位置(x0,y0),探索出一条路径,沿着这条路径骑士能遍历棋盘上的所有单元格。

       (1)编程思路。

        采用深度优先搜索进行路径的探索。深度优先搜索用递归描述的一般框架为:

    void  dfs(int deep)      //  对deep层进行搜索

    {

          if  (符合某种要求||已经不能再搜了)

         {

               按要求进行一些处理,一般为输出;

               return ;

         }

         if   (符合某种条件且有地方可以继续搜索的)   // 这里可能会有多种情况,可能要循环什么的

        {

             vis[x][y]=1;                       //  表示结点(x,y)已访问到

             dfs(deep+1);                    //  搜索下一层

             vis[x][y]=0;                      // 改回来,表示结点(x,y)以后可能被访问
        }
    } 

      定义数组int vis[10][10]记录骑士走到的步数,vis[x][y]=num表示骑士从起点开始走到坐标为(x,y)的格子用了num步(设起点的步数为1)。初始时vis数组元素的值全部为0。

 (2)源程序。

#include <stdio.h>

#include <stdlib.h>

int n,m;

int vis[10][10]={0};

// 定义马走的8个方向

int dir_x[8] = {-1,-2,-2,-1,1,2,2,1};

int dir_y[8] = {2,1,-1,-2,-2,-1,1,2};

void print()

{

       int i,j;

       for(i=0; i<n; i++)

       {

           for(j=0; j<m; j++)

               printf("%3d ",vis[i][j]);

           printf("\n");

        }

}

void dfs(int cur_x,int cur_y,int step)

{

   if(step==n*m+1 )

   {

        print();

        exit(1);

   } 

   int next_x,next_y;

   for(int i=0; i<8; i++)

   {

     next_x = cur_x+dir_x[i];

     next_y = cur_y+dir_y[i];

     if (next_x<0 || next_x>=n || next_y<0 || next_y>=m || vis[next_x][next_y]!=0)

          continue;

     vis[next_x][next_y] = step;

     dfs(next_x,next_y,step+1);

     vis[next_x][next_y] = 0;

   }

}

int main()

{

   printf("请输入棋盘的行数和列数(均小于10):");

   scanf("%d %d",&n,&m);

   printf("请输入出发点坐标:(0—%d,0-%d):",n-1,m-1);

   int x0,y0;

   scanf("%d%d",&x0,&y0);

   vis[x0][y0] = 1;

   dfs(x0,y0,2);

   return 0;

       (3)运行效果。

   DFS(二):骑士游历问题  DFS(二):骑士游历问题

 【例2】a knight's journey(poj 2488)

description
background
the knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey around the world. whenever a knight moves, it is two squares in one direction and one square perpendicular to this. the world of a knight is the chessboard he is living on. our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. can you help this adventurous knight to make travel plans?
problem
find a path such that the knight visits every square once. the knight can start and end on any square of the board.
input
the input begins with a positive integer n in the first line. the following lines contain n test cases. each test case consists of a single line with two positive integers p and q, such that 1 <= p * q <= 26. this represents a p * q chessboard, where p describes how many different square numbers 1, . . . , p exist, q describes how many different square letters exist. these are the first q letters of the latin alphabet: a, . . .
output
the output for every scenario begins with a line containing "scenario #i:", where i is the number of the scenario starting at 1. then print a single line containing the lexicographically first path that visits all squares of the chessboard with knight moves followed by an empty line. the path should be given on a single line by concatenating the names of the visited squares. each square name consists of a capital letter followed by a number.
if no such path exist, you should output impossible on a single line.
sample input
3
1 1
2 3
4 3
sample output
scenario #1:
a1

scenario #2:
impossible

scenario #3:
a1b3c1a2b4c2a3b1c3a4b2c4

      (1)编程思路。

       同样用深度优先搜索。但由于题目要输出字典序最小的,所以遍历时8个方向的偏移组合顺序为:{-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2,-1}, {2,1}。

      (2)源程序。

#include<stdio.h>  

int dir_x[8] = {-2,-2,-1,-1, 1, 1, 2, 2};

int dir_y[8] = {-1, 1,-2, 2,-2, 2,-1, 1};

int vis[27][27]; 

int len,x,y; 

bool flag; 

struct node 

    int x,y; 

}node[1000]; 

void dfs(int cur_x,int cur_y) 

    if(len==x*y) 

    { 

        flag=true; 

        return ; 

    } 

    for(int i=0; i<8; i++) 

    { 

        int next_x=cur_x+dir_x[i]; 

        int next_y=cur_y+dir_y[i]; 

        if(next_x>0 && next_x<=x && next_y>0 && next_y<=y && vis[next_x][next_y]!=1) 

        { 

            node[len].x=next_x; 

            node[len].y=next_y; 

            vis[next_x][next_y]=1; 

            ++len;

            dfs(next_x,next_y); 

            if(len==x*y) 

            { 

                flag=true; 

                return ; 

            } 

            --len; 

            vis[next_x][next_y]=0; 

        } 

    } 

int main() 

    int ncase; 

    int n,i,j; 

    scanf("%d",&ncase); 

    for(n=1; n<=ncase; n++) 

    { 

        flag=false; 

        len=0;

        for (i=0;i<27;i++)

           for (j=0;j<27;j++)

               vis[i][j]=0; 

        node[0].x=1; 

        node[0].y=1; 

        vis[1][1]=1; 

        scanf("%d%d",&y,&x); 

        ++len; 

        dfs(1,1); 

        printf("scenario #%d:\n",n); 

        if(flag==false) 

        { 

            printf("impossible\n\n");

            continue; 

        } 

        for(i=0; i<len; i++) 

        { 

            printf("%c%d",(node[i].x-1)+'a',node[i].y); 

        } 

        printf("\n\n");

            } 

    return 0; 

}