BFS:
起点入队;
开始搜索:
读取队首并出队,搜索范围有四周八个点(有的不存在),搜索到的点入队,并将歩长+1;直到读取的点等于终点;
15MS | 372K |
code:
#include <iostream> #include <string> #include <cstdio> #include <queue> using namespace std; struct point { int x; int y; int step; }st,ed; int x1,y1,x2,y2; bool visit[10][10]; int xx[8] = {1,2,1,2,-1,-2,-1,-2}; int yy[8] = {2,1,-2,-1,2,1,-2,-1}; void bfs() { memset(visit,false,sizeof(visit)); st.x = x1; st.y = y1; st.step = 0; queue <point> p; p.push(st); while(!p.empty()) { ed = p.front(); p.pop(); if(ed.x == x2 && ed.y == y2) break; for(int i = 0; i < 8; i++) { st.x = ed.x + xx[i]; st.y = ed.y + yy[i]; st.step = ed.step + 1; if(!visit[st.x][st.y]&&st.x>0&&st.x<9&&st.y>0&&st.y<9) { visit[st.x][st.y] = true; p.push(st); } } } } int main() { char c1,c2,c; while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF) { x1 = c1 - 'a' + 1; x2 = c2 - 'a' + 1; bfs(); printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,ed.step); getchar(); } }
DFS:
由起点对每个点进行周围8个方位访问,递归调用DFS; 复杂度较高;本题只有8*8,所以能接受;
375MS | 332K |
code:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <iomanip> using namespace std; int r[8][2]={{2,1},{1,2},{-1,2},{-2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1} }; int num[10][10]; void dfs(int x1, int y1, int move) { if(x1<=0 || x1>=9 || y1<=0 || y1>=9||move>=num[x1][y1]) return ; num[x1][y1] = move; for(int i = 0; i < 8; i++) { dfs(x1+r[i][0], y1+r[i][1],move+1); } } int main(int argc, char *argv[]) { int x1,y1,x2,y2; char c1,c2,c; while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF) { x1 = c1 - 'a' + 1; x2 = c2 - 'a' + 1; memset(num,100,sizeof(num)); dfs(x1,y1,0); printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,num[x2][y2]); getchar(); } return 0; }