Algorithm --> 棋盘中求出A到B的最小步数

时间:2023-03-08 15:48:41

求出A到B的最小步数

Algorithm --> 棋盘中求出A到B的最小步数

给定象棋盘,以及位置A和B, 求出从A到B的最小步数

Input
2             -->case 个数
9 9          -->棋盘大小
3 5 2 8    --> 起始位置
20 20
2 3 7 9

Output

代码:

#include <cstdio>
#include <iostream>
#include <string.h> using namespace std;
#define MAX 1000 //八个方向
int o[][] = { { , }, { , - }, { -, }, { -, - }, { -, - }, { -, }, { , - }, { , } }; int R, C;
int _sX, _sY, _eX, _eY; //起始坐标
int graph[MAX][MAX];
int Answer; void DFS( int sX, int sY, int cnt )
{
if( sX < || sX > R || sY < || sY > C )
{
return;
} if( sX == _eX && sY == _eY )
{
if( Answer > cnt ) //求取最小步数 Answer
{
Answer = cnt;
}
} if( graph[sX][sY] == || graph[sX][sY] > cnt ) //当前格子没走或者值比cnt大,取较小值
{
graph[sX][sY] = cnt;
for( int i = ; i < ; i++ )
{
DFS( sX + o[i][], sY + o[i][], cnt + );
}
}
} int main( int argc, char** argv )
{
int tc, T; freopen( "input_chess.txt", "r", stdin ); cin >> T;
for( tc = ; tc < T; tc++ )
{
memset( graph, , sizeof( graph ) ); cin >> R >> C;
cin >> _sX >> _sY >> _eX >> _eY; graph[_sX][_sY] = ; Answer = MAX; DFS( _sX, _sY, ); cout << Answer << endl;
} return ;
}

输入文件: