BFS模板题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
思路:
这题就思路来说,DFS和BFS都可以得到最优解,不过dfs会生成大量重复非最优解,即使优化(用一个二维数组保存到每格的最短时间)也会超时。
下面先附上dfs代码(未AC):
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 #include<queue> 7 using namespace std; 8 int sx, sy, ex, ey, ans = 64; 9 int vis[10][10]; 10 int mov[8][2] = {{-2,+1},{-1,+2},{+1,+2},{+2,+1},{+2,-1},{+1,-2},{-1,-2},{-2,-1}}; 11 12 bool get(int x, int y){ 13 if (x == ex&&y == ey) return true; 14 return false; 15 } 16 17 bool over(int x, int y){ 18 if (x<0||x>=8||y<0||y>=8) return true; 19 return false; 20 } 21 22 void dfs(int cur, int x, int y){ 23 if (cur >= ans) return; 24 if (!vis[x][y]) vis[x][y] = cur; 25 if (get(x, y)){ 26 ans = ans<cur?ans:cur; 27 return; 28 } 29 for (int i = 0; i < 8; i++){ 30 if (!over(x+mov[i][0], y+mov[i][1])&&cur<=vis[x][y]){ 31 vis[x][y] = cur; 32 dfs(cur+1, x+mov[i][0], y+mov[i][1]); 33 } 34 } 35 } 36 37 int main() 38 { 39 freopen("E://in.txt", "r", stdin); 40 char s1, s2, mid; 41 while(scanf("%c%d%c%c%d", &s1, &sy, &mid, &s2, &ey) != EOF){ 42 getchar(); 43 sy -= 1; 44 ey -= 1; 45 sx = s1 - 'a'; 46 ex = s2 - 'a'; 47 dfs(0, sx, sy); 48 printf("To get from %c%d to %c%d takes %d knight moves. ",s1, sy+1, s2, ey+1, ans); 49 ans = 64; 50 memset(vis, 0, sizeof(vis)); 51 } 52 53 return 0; 54 }
用BFS就是一道很简单的模板题了
下面是AC代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 #include<queue> 7 using namespace std; 8 9 int sx, sy, ex, ey, ans; 10 int vis[10][10]; 11 int mov[8][2] = {{-2,+1},{-1,+2},{+1,+2},{+2,+1},{+2,-1},{+1,-2},{-1,-2},{-2,-1}}; 12 13 typedef struct point{ 14 int cur; 15 int x; 16 int y; 17 }point; 18 19 bool get(int x, int y){ 20 if (x == ex&&y == ey) return true; 21 return false; 22 } 23 24 bool over(int x, int y){ 25 if (x<0||x>=8||y<0||y>=8) return true; 26 return false; 27 } 28 29 int bfs(){ 30 queue<point>q; 31 point sta = {0, sx, sy}; 32 q.push(sta); 33 while(!q.empty()){ 34 point now = q.front(); 35 q.pop(); 36 if (get(now.x, now.y)){ 37 ans = now.cur; 38 return 0; 39 } 40 for (int i = 0; i < 8; i++){ 41 int nextx = now.x + mov[i][0], nexty = now.y + mov[i][1]; 42 if (!over(nextx, nexty)&&!vis[nextx][nexty]){ 43 point newp = {now.cur+1, nextx, nexty}; 44 vis[nextx][nexty] = 1; 45 q.push(newp); 46 } 47 } 48 } 49 } 50 51 int main() 52 { 53 //freopen("E://in.txt", "r", stdin); 54 char s1, s2, mid; 55 while(scanf("%c%d%c%c%d", &s1, &sy, &mid, &s2, &ey) != EOF){ 56 getchar(); 57 sy -= 1; 58 ey -= 1; 59 sx = s1 - 'a'; 60 ex = s2 - 'a'; 61 bfs(); 62 printf("To get from %c%d to %c%d takes %d knight moves. ",s1, sy+1, s2, ey+1, ans); 63 memset(vis, 0, sizeof(vis)); 64 ans = 0; 65 } 66 67 return 0; 68 }