深度優先搜索(POJ1164 城堡問題)

深度優先搜索:具體做法就是沿着某條路走到盡頭,如果沒路了,就退回上一步,在尋找其他路線,如果再沒路,繼續退回上一路線,直到最開始。從而達到遍歷的目的。

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;
}

此處的遍歷過程不具有普遍性,因爲題意的規定所有幾個方向的選擇是可以確定的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章