uva439 Knight Moves (搜索 BFS, BFS启蒙题)

来源:互联网 发布:手机上淘宝等级怎么看 编辑:程序博客网 时间:2024/05/28 01:35

题意:HDU1372

思路:HDU1372

算法复杂度: 棋盘是固定的8*8 所有复杂度是常复杂度o(1)。 (不知道这样算对不对, 刚学。 还望大牛指点)

代码:


#include <cstdio>#include <cstring>using namespace std;#define MAX_R 8 #define DIR_NUM 8#define MAX_QUE 2000const int dir[DIR_NUM][2] = {{1,2}, {-1,2}, {1,-2}, {-1,-2}, {2,1}, {-2,1}, {2,-1}, {-2,-1}};struct point{int x;int y;int times;};point star, end;bool vis[MAX_R + 3][MAX_R + 3];int BFS();int main(){char x1, x2;int y1, y2;while (scanf("%c%d %c%d%*c", &x1, &y1, &x2, &y2) == 4) {// initmemset(vis, 0, sizeof(vis));star.x = x1 - 96;// 'a' - 1 = 96star.y = y1;star.times = 0;end.x = x2 - 96;end.y = y2;end.times = 0;// outputprintf("To get from %c%d to %c%d takes %d knight moves.\n", x1, y1, x2, y2, BFS());}return 0;}int BFS(){if (star.x == end.x && star.y == end.y) {return 0;}point *que[MAX_QUE];int head = 0;    inttail = 0;que[tail++] = ☆while (head < tail) {point *root = que[head++];if (root->x == end.x && root->y == end.y) {return root->times;}for (int i = 0; i < DIR_NUM; i++) {point *child = new point;child->x = root->x + dir[i][0];child->y = root->y + dir[i][1];child->times = root->times;if (child->x >= 1 && child->x <= MAX_R && child->y >= 1 && child->y <= MAX_R && vis[child->x][child->y] == 0) {vis[child->x][child->y] = 1;child->times++;que[tail++] = child;}}}}

原创粉丝点击