BFS。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 #define MAXN 305 8 9 typedef struct node_st { 10 int x, y; 11 node_st() {} 12 node_st(int xx, int yy) { 13 x = xx; y = yy; 14 } 15 } node_st; 16 17 char map[MAXN][MAXN]; 18 bool visit[MAXN][MAXN]; 19 int direct[4][2] = {-1,0,1,0,0,-1,0,1}; 20 int n, m, f, s; 21 22 bool getNext(int *x, int *y) { 23 for (int i=0; i<n; ++i) { 24 for (int j=0; j<m; ++j) { 25 if (map[i][j]!=‘#‘ && visit[i][j]==false) { 26 *x = i; 27 *y = j; 28 return true; 29 } 30 } 31 } 32 return false; 33 } 34 35 void bfs() { 36 queue<node_st> que; 37 node_st node; 38 int ff, ss, x, y; 39 bool flg; 40 int i; 41 42 f = s = 0; 43 memset(visit, false, sizeof(visit)); 44 while (1) { 45 if (!getNext(&x, &y)) 46 break; 47 ff = ss = 0; 48 if (map[x][y] == ‘o‘) ++ff; 49 if (map[x][y] == ‘v‘) ++ss; 50 que.push(node_st(x, y)); 51 visit[x][y] = true; 52 flg = false; 53 54 while (!que.empty()) { 55 node = que.front(); 56 que.pop(); 57 for (i=0; i<4; ++i) { 58 x = node.x + direct[i][0]; 59 y = node.y + direct[i][1]; 60 if (x<0 || x>=n || y<0 || y>=m) { 61 flg = true; 62 continue; 63 } 64 if (map[x][y]!=‘#‘ && !visit[x][y]) { 65 que.push(node_st(x, y)); 66 visit[x][y] = true; 67 if (map[x][y] == ‘o‘) ++ff; 68 if (map[x][y] == ‘v‘) ++ss; 69 } 70 } 71 } 72 if (!flg) { 73 if (ff > ss) f += ff; 74 if (ff < ss) s += ss; 75 } 76 } 77 printf("%d %d\n", f, s); 78 } 79 80 int main() { 81 int i; 82 83 while (scanf("%d %d", &n, &m) != EOF) { 84 for (i=0; i<n; ++i) 85 scanf("%s", map[i]); 86 bfs(); 87 } 88 89 return 0; 90 }
【HDOJ】2267 How Many People Can Survive,布布扣,bubuko.com
【HDOJ】2267 How Many People Can Survive
原文地址:http://www.cnblogs.com/bombe1013/p/3843847.html