acm algorithm practice Jan 3 DFS

本文探讨了骑士周游问题,一种经典的棋盘遍历问题,通过深度优先搜索(DFS)和回溯算法寻找使骑士访问棋盘上每个格子恰好一次的路径。提供了详细的伪代码与实现思路,适用于算法学习与竞赛。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

poj 2488 knight's journey

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.

-------------------------------------------------

simple DFS problem, the key is "trace back"

pseudocode for DFS with traceback:

bool dfs(point p)

{

  if (the count == total squares)

  {

    print and return true;

  }

  // 8 moving method

  for each moving method 

    if the p' is white && not exceed the boundary

      p'.color <----- grey

      count ++

      inqueue(p')

      if (dfs(p') == true)   // which means  if the the bottom recursion return the true, no need to traceback 

        return true 

      p'.color <----white  //trace back 

      count --

      dequeue(p')

 

  return false

}

more convient way is to use recursion times replace count, it is a traditional recursive problem. 

bool dfs( int dip, int x, int y )
{
 if( dip == n )
 {
    int j;
    for( j = 0; j<dip; j++ )//找到答案则输出路径
    {
     printf( "%c%d", path[j].y+'A', path[j].x+1 );
    }
    cout << endl;
    return true;
 }
 int i;
 for( i = 0; i<8; i++ )
 {
    int tx, ty;
    tx = x + a_x[i];
    ty = y + a_y[i];
    if( !isover(tx, ty) && !f[ty][tx] )
    {
     f[ty][tx] = true;
     path[dip].x = tx;
     path[dip].y = ty;
     if( dfs( dip+1, tx, ty ) )
      return true;
     f[ty][tx] = false;//算是回朔吧
    }
 }
 return false;
}

here, since dip stands for the recursion times. and we use path[] record the path. it is not necessary to delete the value in path[] in traceback stage (the new data will overwrite the old error one)

转载于:https://www.cnblogs.com/ggppwx/archive/2011/01/05/1925974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值