码迷,mamicode.com
首页 > 其他好文 > 详细

搜索专题(不定期更新)

时间:2017-07-09 12:33:52      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:int   namespace   cin   close   sed   names   void   splay   位置   

 1、POJ 2386  Lake Counting

  题意:给出一块区域,询问有多少个湖泊?

  思路: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

 2、POJ  1979  Red and Black

  题意:求从‘@’出发,每次只能从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

搜索专题(不定期更新)

标签:int   namespace   cin   close   sed   names   void   splay   位置   

原文地址:http://www.cnblogs.com/ivan-count/p/7140702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!