Red and Black

1 #include <iostream>
2 #include <queue>
3 using namespace std;
4
5
6 int m, n, s1, s2;
7 struct Node{
8 int i;
9 int j;
10 };
11 char map[30][30];
12 bool visited[30][30];
13 int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
14
15 int bfs(int s1, int s2)
16 {
17 memset(visited, 0, sizeof(visited));
18 int count = 0;
19 Node a;
20 a.i = s1;
21 a.j = s2;
22 visited[a.i][a.j] = 1;
23 queue<Node> q;
24 q.push(a);
25 count++;
26 while(!q.empty())
27 {
28 a = q.front();
29 q.pop();
30 for(int i = 0; i < 4; ++i)
31 {
32 int xx = a.i + dir[i][0];
33 int yy = a.j + dir[i][1];
34 if(xx >= 0 && xx < m && yy >= 0 && yy < n)
35 {
36 if(map[xx][yy] == '.' && visited[xx][yy] == 0)
37 {
38 Node b;
39 b.i = xx;
40 b.j = yy;
41 q.push(b);
42 visited[xx][yy] = 1;
43 count++;
44 }
45 }
46 }
47 }
48 return count;
49 }
50 int main()
51 {
52 while(scanf("%d%d", &n, &m) && (n || m))
53 {
54 getchar();
55 for(int i = 0; i < m; ++i)
56 {
57 for(int j = 0; j < n; ++j)
58 {
59 map[i][j] = getchar();
60 if(map[i][j] == '@')
61 {
62 s1 = i;
63 s2 = j;
64 }
65 }
66 getchar();
67 }
68 cout << bfs(s1, s2) << endl;
69 }
70 return 0;
71 }
经过BFS的一系列训练,20分钟搞定,凑活吧
posted @ 2011-07-09 22:42  georgechen_ena  阅读(65)  评论(0)    收藏  举报