http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2081
纠结一个晚上的题目..竟然同时使用了BFS和DFS.菜鸟花了一个晚上才醒悟过来..
好吧..终于了解了DFS和BFS之间的区别了..oh yeah~~
/* * 2081.cpp * * Created on: Apr 30, 2010 * Author: wyy * */ #define MaxVertexs 10 #include<cstdio> #include<queue> using namespace std; struct point { int x, y; }; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; point S, T, B[80]; int N, M, repeat, MinDis, Count, Sum, Bn; int dis[MaxVertexs][MaxVertexs]; char graph[MaxVertexs][MaxVertexs]; bool visited[MaxVertexs][MaxVertexs]; void Read() { Bn = Count = Sum = 0; scanf("%d%d", &N, &M); getchar(); for(int i = 0; i < N; ++i) { gets(graph[i]); for(int j = 0; j < M; ++j) { dis[i][j] = 0; if(graph[i][j] == 'S') { S.x = i; S.y = j; } else if(graph[i][j] == 'T') { T.x = i; T.y = j; } else if(graph[i][j] == 'M') { ++Bn; B[Bn].x = i; B[Bn].y = j; } } } } void Init() { for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) visited[i][j] = false; visited[S.x][S.y] = true; } bool IsValid(const point &p) { return (p.x > 0 && p.y > 0 && p.x < N - 1 && p.y < M - 1 && graph[p.x][p.y] != '#' && !visited[p.x][p.y]); } void BFS() { point m, n; queue<point> Q; Q.push(S); while(!Q.empty()) { m = Q.front(); Q.pop(); for(int i = 0; i < 4; ++i) { n.x = m.x + dx[i]; n.y = m.y + dy[i]; if(IsValid(n)) { dis[n.x][n.y] = dis[m.x][m.y] + 1; visited[n.x][n.y] = true; Q.push(n); } } } MinDis = dis[T.x][T.y]; } void DFS(int size, int c, point p) { if(size == MinDis && p.x == T.x && p.y == T.y) { ++Sum; if(c > 0) ++Count; } else if(size < MinDis) { point m; for(int i = 1; i <= Bn; ++i) if(p.x == B[i].x && p.y == B[i].y) { ++c; break; } for(int i = 0; i < 4; ++i) { m.x = p.x + dx[i]; m.y = p.y + dy[i]; if(IsValid(m)) { visited[m.x][m.y] = true; DFS(size + 1, c, m); visited[m.x][m.y] = false; } } } } void Solve(int k) { Read(); Init(); BFS(); Init(); DFS(0, 0, S); printf("Mission #%d:/n", k + 1); if(Sum > Count) printf("The probability for the spy to get to the telegraph transmitter is %.2lf%%./n/n", 100.0 * (Sum - Count) / Sum); else printf("Mission Impossible./n/n"); } int main() { //freopen("input.txt", "r", stdin); scanf("%d", &repeat); for(int i = 0; i < repeat; ++i) Solve(i); //fclose(stdin); return 0; }