zoj 1091 Knight Moves

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=91

 

简单的BFS题.只要知道马是走"日"字的就行了.

 

/* * 1091.cpp * * Created on: Apr 29, 2010 * Author: wyy * */ #include<cstdio> #include<queue> using namespace std; struct point { int x, y, num; }; int dx[8] = {1, 1, -1, -1, 2, -2, 2, -2}; int dy[8] = {2, -2, 2, -2, 1, 1, -1, -1}; bool visited[8][8]; point p1, p2; char str1[3], str2[3]; void Init() { for(int i = 0; i < 8; ++i) for(int j = 0; j < 8; ++j) visited[i][j] = false; p1.x = str1[0] - 'a'; p2.x = str2[0] - 'a'; p1.y = str1[1] - '1'; p2.y = str2[1] - '1'; p1.num = 0; visited[p1.x][p1.y] = true; } bool IsValid(point p) { return (p.x >= 0 && p.y >= 0 && p.x < 8 && p.y < 8); } void BFS() { queue<point> Q; point m, n; Q.push(p1); while(!Q.empty()) { m = Q.front(); if(m.x == p2.x && m.y == p2.y) { printf("To get from %s to %s takes %d knight moves./n", str1, str2, m.num); break; } Q.pop(); for(int i = 0; i < 8; ++i) { n.x = m.x + dx[i]; n.y = m.y + dy[i]; if(IsValid(n) && !visited[n.x][n.y]) { visited[n.x][n.y] = true; n.num = m.num + 1; Q.push(n); } } } } int main() { //freopen("input.txt", "r", stdin); while(scanf("%s%s", str1, str2) != EOF) { Init(); BFS(); } //fclose(stdin); return 0; }

你可能感兴趣的:(zoj 1091 Knight Moves)