HDU ACM 1198 Farm Irrigation(BFS)
http://acm.hdu.edu.cn/showproblem.php?pid=1198
题意:输入A~K 各代表一个图形,判断有多少个联通分支
听说用DFS比较简单,但是还是用了BFS
定义一个函数 way() 判断向四个方向是否联通
BFS中用四句if语句(可优化)判断当前位置能不能走到下一个位置 和 下个位置能不能走到当前位置
View Code
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 struct Node 5 { 6 int x; 7 int y; 8 }; 9 char map[55][55]; 10 int used[55][55]; 11 12 bool way(int x,int y,int w) 13 { 14 if(w == 0 && (map[x][y] == 'A' || map[x][y] == 'B' || map[x][y] == 'E' 15 || map[x][y] == 'G' || map[x][y] == 'H' || map[x][y] == 'J' || map[x][y] == 'K' )) 16 { 17 return 1; 18 } 19 if(w == 1 && (map[x][y] == 'C' || map[x][y] == 'D' || map[x][y] == 'E' 20 || map[x][y] == 'H' || map[x][y] == 'I' || map[x][y] == 'J' || map[x][y] == 'K' )) 21 { 22 return 1; 23 } 24 if(w == 2 && (map[x][y] == 'A' || map[x][y] == 'C' || map[x][y] == 'F' 25 || map[x][y] == 'G' || map[x][y] == 'H' || map[x][y] == 'I' || map[x][y] == 'K' )) 26 { 27 return 1; 28 } 29 if(w == 3 && (map[x][y] == 'B' || map[x][y] == 'D' || map[x][y] == 'F' 30 || map[x][y] == 'G' || map[x][y] == 'I' || map[x][y] == 'J' || map[x][y] == 'K' )) 31 { 32 return 1; 33 } 34 return 0; 35 } 36 int BFS(int x,int y) 37 { 38 memset(used,0,sizeof(used)); 39 queue <Node> q; 40 int i,j; 41 Node a,b,c; 42 int sum =0; 43 while(1) 44 { 45 46 int mark = 0; 47 for(i=0;i<x;i++) 48 { 49 for(j=0;j<y;j++) 50 { 51 if(!used[i][j]) 52 { 53 mark = 1; 54 a.x = i; 55 a.y = j; 56 q.push(a); 57 used[a.x][a.y] = 1; 58 break; 59 } 60 } 61 if(mark == 1) 62 { 63 break; 64 } 65 } 66 67 if(mark == 0) 68 { 69 return sum; 70 } 71 sum++; 72 while(!q.empty()) 73 { 74 b=q.front(); 75 q.pop(); 76 77 c.x = b.x + -1; 78 c.y = b.y + 0; 79 if(way(b.x,b.y,0) && way(c.x,c.y,1) && c.x>=0 && c.y>=0 && c.x<x && c.y<y && !used[c.x][c.y]) 80 { 81 q.push(c); 82 used[c.x][c.y] = 1; 83 } 84 85 c.x = b.x + 1; 86 c.y = b.y + 0; 87 if(way(b.x,b.y,1) && way(c.x,c.y,0) && c.x>=0 && c.y>=0 && c.x<x && c.y<y && !used[c.x][c.y]) 88 { 89 q.push(c); 90 used[c.x][c.y] = 1; 91 } 92 93 c.x = b.x + 0; 94 c.y = b.y + -1; 95 if(way(b.x,b.y,2) && way(c.x,c.y,3) && c.x>=0 && c.y>=0 && c.x<x && c.y<y && !used[c.x][c.y]) 96 { 97 q.push(c); 98 used[c.x][c.y] = 1; 99 } 100 101 c.x = b.x + 0; 102 c.y = b.y + 1; 103 if(way(b.x,b.y,3) && way(c.x,c.y,2) && c.x>=0 && c.y>=0 && c.x<x && c.y<y && !used[c.x][c.y]) 104 { 105 q.push(c); 106 used[c.x][c.y] = 1; 107 } 108 } 109 } 110 return -1; 111 } 112 int main() 113 { 114 115 int x,y; 116 while(cin>>x>>y) 117 { 118 memset(map,0,sizeof(map)); 119 if(x == -1 && y == -1) 120 { 121 return 0; 122 } 123 int i,j; 124 for(i=0;i<x;i++) 125 { 126 for(j=0;j<y;j++) 127 { 128 cin>>map[i][j]; 129 } 130 } 131 cout<<BFS(x,y)<<endl; 132 } 133 return 0; 134 }