深度優先搜索:具體做法就是沿着某條路走到盡頭,如果沒路了,就退回上一步,在尋找其他路線,如果再沒路,繼續退回上一路線,直到最開始。從而達到遍歷的目的。
DFS模板:
DFS(v)
{
if(v被訪問過)
{
return;
}
將v標記爲訪問過;
對於與v相鄰的每一個點u:DFS(u);
}
int main()
{
while(v是未標記過的點)
{
DFS(V)
}
return 0;
}
例題:POJ1164
題目大意是要尋找城堡中的房間數,和房間的最大面積。#是牆,1,2,4,8分別代表西北東南方向的值,每個框讀入的值都是它四周的牆的值的和!
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
Output
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;
}
此處的遍歷過程不具有普遍性,因爲題意的規定所有幾個方向的選擇是可以確定的。