您的位置:首页 > 编程语言 > C语言/C++

C++搜索与回溯算法之The Castle

2017-06-24 14:12 471 查看

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啦,ㄟ(≧◇≦)ㄏ
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ dfs 回溯 深搜 算法