439 - Knight Moves
来源:互联网 发布:程序员试用期总结 编辑:程序博客网 时间:2024/06/05 22:46
这是一道简单的最短路的问题,由于地图较小,用深度遍历和广度遍历应该都不会超时,此处使用广度遍历作为示范:
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
int web[10][10];
void getpos(char* inp, int &x, int &y)
{
x = inp[0]-'a'+1;
y = inp[1]-'0';
}
int bfs(pair<int, int> st, pair<int, int> ed)
{
web[st.first][st.second] = 0;
queue<pair<int, int> > qe;
qe.push(st);
while(!qe.empty())
{
pair<int, int> temp=qe.front();
int stp = web[temp.first][temp.second];
if(temp == ed)
return stp;
++stp;
qe.pop();
for(int i = -2; i <= 2; ++i)
for(int j = -2; j <= 2; ++j)
{
if(i && j && abs(i) != abs(j) && temp.first+i >=1 && temp.first+i <= 8 && temp.second+j >=1 && temp.second+j <= 8)
{
if(!web[temp.first+i][temp.second+j])
{
//printf("=| %d %d %d %d\n", temp.first+i, temp.first+j, i, j)
web[temp.first+i][temp.second+j] = stp;
qe.push(make_pair(temp.first+i, temp.second+j));
if(make_pair(temp.first+i, temp.second+j) == ed)
return stp;
}
}
}
}
return 0;
}
const int inf = 1<<30;
int main()
{
//InIt
char st[5], to[5];
while(~scanf("%s %s", st, to))
{
memset(web, 0, sizeof(web));
int stx, sty, tox, toy;
getpos(st, stx, sty);
getpos(to, tox, toy);
// printf("%d %d %d %d\n", stx, sty, tox, toy);
printf("To get from %s to %s takes %d knight moves.\n", st, to, bfs(make_pair(stx, sty) ,make_pair(tox, toy)));
}
return 0;
}
- uva 439 knight moves
- uva 439 - Knight Moves
- 439 - Knight Moves
- uva 439 - Knight Moves
- uva 439 - Knight Moves
- UVaOJ 439 - Knight Moves
- uva 439 - Knight Moves
- uva-439 - Knight Moves
- UVa 439 - Knight Moves
- UVa 439 - Knight Moves
- 439 - Knight Moves
- UVA 439 - Knight Moves
- 439 - Knight Moves//bfs
- uva 439 Knight Moves
- UVa 439 - Knight Moves
- uva 439 - Knight Moves
- UVa:439 Knight Moves
- uva 439 - Knight Moves
- IAP(程序内购买): 完全攻略
- 同步和信号量
- JavaScript向php传递参数
- 那些年,在nodejs上踩过的坑(一)
- Linux中替换文本中的字符串
- 439 - Knight Moves
- HDU 5298 Solid Geometry Homework(异或)
- iOS中使用七牛云存储Django服务端实现简单的图片上传功能
- java.sql.SQLException: Parameter metadata not available for the given statement
- C语言-变量的存储类别(auto, static, register, extern)
- Store Kit Guide(In App Purchase)翻译
- 暑假集训第四周阶段一 DP A - Robberies
- opencv——PNG格式图像读取转换函数
- C++第七节:继承