1. 程式人生 > >C++搜尋與回溯演算法之The Castle

C++搜尋與回溯演算法之The Castle



The Castle

(想看翻譯的朋友,請單擊;想看程式碼的朋友,請單擊)

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. n≤50)

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

8
389 207 155 300 299 170 158 65

程式碼

I'm so busy that I don't want to tell you the thread of the problem.

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int m,n,ans,cnt,bigest; //變數比較亂,慢慢領悟(*^__^*) 嘻嘻……
bool flag[100][100],mark[100][100][4];
int map[105][105];
int wayr[4]={0,1,0,-1},wayc[4]={1,0,-1,0}; //此方向不可改,( ⊙o⊙ )千真萬確
bool check(int a,int b,int x) //判斷函式,一次性囊括所有判斷(包括剪枝),~\(≧▽≦)/~啦啦啦
{
    if(a<m&&b<n&&a>=0&&b>=0&&mark[a][b][x]&&!flag[a][b]) return 1;
    return 0;
}
void dfs(int r,int c) //深搜函式,內部構造簡單,~O(∩_∩)O~
{
    for(int i=0;i<4;i++)
        if(check(r+wayr[i],c+wayc[i],i))
        {
            flag[r+wayr[i]][c+wayc[i]]=1;
            cnt++;
            dfs(r+wayr[i],c+wayc[i]);
        }
}
int main()
{
    scanf("%d%d",&m,&n);
    for(int i=0;i<m;i++) //輸入並構造"城堡",別捉急,慢慢看,╰( ̄▽ ̄)╭
        for(int j=0;j<n;j++)
        {
            scanf("%d",&map[i][j]);
            if(!(map[i][j]&1)) mark[i][j][0]=1;
            if(!(map[i][j]&2)) mark[i][j][1]=1;
            if(!(map[i][j]&4)) mark[i][j][2]=1;
            if(!(map[i][j]&8)) mark[i][j][3]=1;
        }
    for(int i=0;i<m;i++) //開始運算,d=====( ̄▽ ̄*)b
        for(int j=0;j<n;j++)
            if(!flag[i][j])
            {
                flag[i][j]=1;
                cnt=1;
                dfs(i,j);
                if(cnt>bigest) bigest=cnt; //找最大,(~ ̄▽ ̄)~
                ans++;
            }
    printf("%d\n%d\n",ans,bigest); //♪(^∇^*),AC啦,ㄟ(≧◇≦)ㄏ
}