标签:map include && int Knight dx dy Moves
Knight Moves
依葫芦画瓢,葫芦在这里:
Dungeon Master
代码几乎一样的套路吧~再注意两点:
- 注意行列与自己设的 x y 坐标的关系!!(竖 x 横 y)
- 注意每一次循环将队列清空:
while(!q.empty()) q.pop();
否则会报错:Runtime error!
//比葫芦画瓢 (高仿 Dungeon Master)
//还是注意分清坐标与行列的关系!!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[5], e[5];
int map[10][10];
struct coor {
int x, y;
};
int sx, sy, ex, ey;
queue<coor>q;
int mx[] = { 2,2,1,1,-1,-1,-2,-2 };
int my[] = { 1,-1,2,-2,2,-2,1,-1 };
void bfs() {
while (!q.empty()) {
coor g = q.front();
q.pop();
//if(g.x==ex&&g.y==ey) break;//加上这一句就错了,本来想简化搜索次数。。(暂时不知道为什么!现在先让搜索进行到底!!)
for (int i = 0;i < 8;i++) {
int dx = g.x + mx[i];
int dy = g.y + my[i];
if (dx > 0 && dy > 0 && dx < 9 && dy < 9 && map[dx][dy] == -1) {
map[dx][dy] = map[g.x][g.y] + 1;
coor h;
h.x = dx;h.y = dy;
q.push(h);
}
}
}
cout << "To get from " << s[0] << s[1] << " to " << e[0] << e[1] << " takes " << map[ex][ey] << " knight moves." << endl;
}
int main() {
while (scanf("%s%s", s, e) != EOF) {
memset(map, -1, sizeof(map));
while (!q.empty()) q.pop();//不加这一句会报错:Runtime error,注意每一轮清空队列!!!
sy = s[0] - 'a' + 1;sx = s[1] - '0';// x 竖 y 横!!(分清)
ey = e[0] - 'a' + 1;ex = e[1] - '0';
coor g;
g.x = sx;g.y = sy;
map[sx][sy] = 0;
q.push(g);
bfs();
}
return 0;
}
标签:map,include,&&,int,Knight,dx,dy,Moves 来源: https://blog.csdn.net/interestingddd/article/details/119117538
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。