题意:给出一块区域,询问有多少个湖泊?
思路:DFS,对于‘W’,深搜一次,并标记已访问。之后每次对未访问的‘W’做一次深搜。
1 #include<iostream> 2 #include<memory.h> 3 using namespace std; 4 char lake[105][105]; 5 bool vis[105][105]; 6 int n, m; 7 void DFS(int r, int c) 8 { 9 if (r >=n || r<0 || c>=m || c < 0) return; 10 if (lake[r][c] == ‘W‘&&!vis[r][c]) 11 { 12 vis[r][c] = true; 13 DFS(r + 1, c); 14 DFS(r - 1, c); 15 DFS(r, c + 1); 16 DFS(r, c - 1); 17 DFS(r + 1, c + 1); 18 DFS(r + 1, c - 1); 19 DFS(r - 1, c + 1); 20 DFS(r - 1, c - 1); 21 } 22 } 23 int main() 24 { 25 while (cin >> n >> m) 26 { 27 memset(lake, 0, sizeof(lake)); 28 memset(vis, 0, sizeof(vis)); 29 for (int i = 0; i < n; i++) 30 { 31 for (int j = 0; j < m; j++) 32 { 33 cin >> lake[i][j]; 34 } 35 } 36 int num = 0; 37 for (int i = 0; i < n; i++) 38 { 39 for (int j = 0; j < m; j++) 40 { 41 if (lake[i][j] == ‘W‘ && !vis[i][j]) 42 { 43 DFS(i, j); 44 num++; 45 } 46 } 47 } 48 cout << num << endl; 49 } 50 return 0; 51 }
POJ 2386 Lake Counting
题意:求从‘@’出发,每次只能从4个方向走,且只能走到‘.’的位置,求全部能走到的个数。
思路:从‘@’出发DFS一遍即可。
1 #include<iostream> 2 using namespace std; 3 char m[25][25]; 4 int w, h; 5 int ans; 6 void DFS(int r,int c) 7 { 8 if (r >= h || r < 0 || c >= w || c < 0) return; 9 if (m[r][c] == ‘#‘) return; 10 else 11 { 12 m[r][c] = ‘#‘; 13 ans++; 14 DFS(r + 1, c); 15 DFS(r - 1, c); 16 DFS(r, c + 1); 17 DFS(r, c - 1); 18 } 19 } 20 int main() 21 { 22 while (cin >> w >> h, w != 0 && h != 0) 23 { 24 int sr, sc; 25 for (int i = 0; i < h; i++) 26 { 27 for (int j = 0; j < w; j++) 28 { 29 cin >> m[i][j]; 30 if (m[i][j] == ‘@‘) sr = i, sc = j; 31 } 32 } 33 ans = 0; 34 DFS(sr,sc); 35 cout << ans << endl; 36 } 37 return 0; 38 }
POJ 1979 Red and Black
时间: 2024-10-06 15:06:45