Knight Moves的BFS算法和DFS
可以理解成八叉树
进行层次遍历。
#include <iostream> #include<string> #include<queue> using namespace std; #define MAXSTEP 0x7fffffff; int step=MAXSTEP;//用于DFS中的计算步数 int visit[8][8];//记录点的访问 int rules[8][2] = { {-1,2},{-2,1},{-2,-1},{-1,-2},{1,2},{2,1},{2,-1},{1,-2} };//从左上到左下,再从右上到右下 struct point{ int x;//x坐标 int y;//y坐标 int step;//点所在八叉树的层数,也是起始点到当前点的步数 }; bool operator ==(const point& l, const point& r) { return (l.x == r.x && l.y == r.y) ? true : false; } bool isLegal(point p) {//判断当前点是否合法 return p.x >= 0 && p.x <= 7 && p.y >= 0 && p.y <= 7 ? true : false; } void BFS(point start, point end) { start.step = 0;//一开始的点就是起始点,起始点到自己的步数当然是0 //到终点了 if (start == end) { if (start.step < step) { step = start.step; } return; } //不合法 if (!isLegal(start) || !isLegal(end)) return; queue<point> q; q.push(start); while (!q.empty()) { point current = q.front(); q.pop(); if (!isLegal(current)) continue; if (current == end) { if (current.step < step) { step = current.step; } return; } for (int n = 0; n < 8; n++) { point newStart; newStart.x = current.x + rules[n][0]; newStart.y = current.y + rules[n][1]; newStart.step = current.step + 1; q.push(newStart); } } } int main() { for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; j++) { visit[i][j] = 0; } } string a, b; point origin, fin; while (cin >> a >> b) { origin.x = a[1] - '1'; origin.y = a[0] - 'a'; fin.x = b[1] - '0' - 1; fin.y = b[0] - 'a'; BFS(origin, fin); cout << "To get from " << a << " to " << b << " takes " << step << " knight moves." << endl; step = MAXSTEP; } }
DFS
#include<cstdio> #include<iostream> using namespace std; int maps[8][8] = {0}; static int dir[2][8] = {{-1, -1, +1, +1, -2, -2, +2, +2}, {-2, +2, -2, +2, -1, +1, -1, +1}}; int x2, y2; int minClue; bool isThere(int x, int y){ if(x < 0 || x > 7){ return false; } if(y < 0 || y > 7){ return false; } return true; } int DFS(int x, int y, int l) { if(x==x2&&y==y2 && minClue > l){ //printf("x:%d y:%d ", x2, y2); minClue = l; return 0; } if(maps[x][y] > l && isThere(x, y)){ maps[x][y] = l; for(int i=0; i<8; i++){ DFS(x+dir[0][i], y+dir[1][i], l+1); } } } void init() { minClue = 10000; for(int i=0; i<8; i++){ for(int j=0; j<8; j++){ maps[i][j]=100; } } return; } int main() { char s1[5]; char s2[5]; int x1,y1; while(cin>>s1>>s2){ init(); x1 = (int)(s1[0]-'a'); y1 = (int)(s1[1]-'1'); x2 = (int)(s2[0]-'a'); y2 = (int)(s2[1]-'1'); DFS(x1, y1, 0); printf("To get from %s to %s takes %d knight moves. ",s1,s2, minClue); } return 0; }