您的位置:首页 > 其它

深度优先搜索(POJ1164 城堡问题)

2015-12-16 20:04 351 查看
深度优先搜索:具体做法就是沿着某条路走到尽头,如果没路了,就退回上一步,在寻找其他路线,如果再没路,继续退回上一路线,直到最开始。从而达到遍历的目的。

DFS模板:

 DFS(v)
 {
     if(v被访问过)
     {
         return;
     }
     将v标记为访问过;
     对于与v相邻的每一个点u:DFS(u);
 }
 
 int main()
 {
     while(v是未标记过的点)
     {
         DFS(V)
     }
     return 0;
 }


例题:POJ1164

题目大意是要寻找城堡中的房间数,和房间的最大面积。#是墙,1,2,4,8分别代表西北东南方向的值,每个框读入的值都是它四周的墙的值的和!

The Castle

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 6936 Accepted: 3888
Description

1   2   3   4   5   6   7

#############################

1 #   |   #   |   #   |   |   #

#####---#####---#---#####---#

2 #   #   |   #   #   #   #   #

#---#####---#####---#####---#

3 #   |   |   #   #   #   #   #

#---#########---#####---#---#

4 #   #   |   |   |   |   #   #

#############################

(Figure 1)

#  = Wall

|  = No wall

-  = No wall


Figure 1 shows the map of a castle.Write a program that calculates

1. how many rooms the castle has

2. how big the largest room is

The castle is divided into m * n (m<=50, n<=50) square modules. Each such module can have between zero and four walls.

Input
Your program is to read from standard input. The first line contains the number of modules in the north-south direction and the number of modules in the east-west direction. In the following lines each module is described by a
number (0 <= p <= 15). This number is the sum of: 1 (= wall to the west), 2 (= wall to the north), 4 (= wall to the east), 8 (= wall to the south). Inner walls are defined twice; a wall to the south in module 1,1 is also indicated as a wall to the north in
module 2,1. The castle always has at least two rooms.
Output
Your program is to write to standard output: First the number of rooms, then the area of the largest room (counted in modules).
Sample Input
4
7
11 6 11 6 3 10 6
7 9 6 13 5 15 5
1 10 12 7 13 7 5
13 11 10 8 10 12 13

Sample Output
5
9


解答:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int rooms[60][60];
int color[60][60] = {0};
int a, b;
int roomnum = 0, roomarea = 0, maxn = 0;

void DFS(int i, int j)
{
if(color[i][j])
return;
++roomarea;
color[i][j] = roomnum;
if((rooms[i][j] & 1) == 0)  DFS(i, j-1);
if((rooms[i][j] & 2) == 0)  DFS(i-1, j);
if((rooms[i][j] & 4) == 0)  DFS(i, j+1);
if((rooms[i][j] & 8) == 0)  DFS(i+1, j);
}

int main()
{
cin >> a >> b;
for(int i = 1; i <= a; i++)
{
for(int j = 1; j <= b; j++)
{
scanf("%d", &rooms[i][j]);
}
}
for(int i = 1; i <= a; i++)
{
for(int j = 1; j <= b; j++)
{
if(!color[i][j])
{
roomnum++;
roomarea = 0;
DFS(i, j);
}
maxn = max(maxn, roomarea);
}
}
cout << roomnum << endl << maxn << endl;
return 0;
}


此处的遍历过程不具有普遍性,因为题意的规定所有几个方向的选择是可以确定的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息