您的位置:首页 > 编程语言 > Go语言

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

2015-09-07 11:20 483 查看
[b]求出A到B的最小步数[/b]



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

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

Output
2

5

代码:

#include <cstdio>
#include <iostream>
#include <string.h>

using namespace std;
#define MAX 1000

//八个方向
int o[8][2] = { { 1, 2 }, { 1, -2 }, { -1, 2 }, { -1, -2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } };

int R, C;
int _sX, _sY, _eX, _eY;  //起始坐标
int graph[MAX][MAX];
int Answer;

void DFS( int sX, int sY, int cnt )
{
if( sX < 1 || sX > R || sY < 1 || sY > C )
{
return;
}

if( sX == _eX && sY == _eY )
{
if( Answer > cnt )     //求取最小步数 Answer
{
Answer = cnt;
}
}

if( graph[sX][sY] == 0 || graph[sX][sY] > cnt )  //当前格子没走或者值比cnt大,取较小值
{
graph[sX][sY] = cnt;
for( int i = 0; i < 8; i++ )
{
DFS( sX + o[i][0], sY + o[i][1], cnt + 1 );
}
}
}

int main( int argc, char** argv )
{
int tc, T;

freopen( "input_chess.txt", "r", stdin );

cin >> T;
for( tc = 0; tc < T; tc++ )
{
memset( graph, 0, sizeof( graph ) );

cin >> R >> C;
cin >> _sX >> _sY >> _eX >> _eY;

graph[_sX][_sY] = 1;

Answer = MAX;

DFS( _sX, _sY, 0 );

cout << Answer << endl;
}

return 0;
}


输入文件:

5
10 10
1 1 10 10
20 20
2 3 7 9
30 30
2 15 29 29
40 40
2 3 1 40
45 45
40 10 27 40
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: