题目描述
不是任何人都可以进入桃花岛的,黄药师最讨厌象郭靖一样呆头呆脑的人。所以,他在桃花岛的唯一入口处修了一条小路,这条小路全部用正方形瓷砖铺设而成。有的瓷砖可以踩,我们认为是安全的,而有的瓷砖一踩上去就会有喷出要命的毒气,那你就死翘翘了,我们认为是不安全的。你只能从一块安全的瓷砖上走到与他相邻的四块瓷砖中的任何一个上,但它也必须是安全的才行。
由于你是黄蓉的朋友,她事先告诉你哪些砖是安全的、哪些砖是不安全的,并且她会指引你飞到第一块砖上(第一块砖可能在任意安全位置),现在她告诉你进入桃花岛的秘密就是:如果你能走过最多的瓷砖并且没有死,那么桃花岛的大门就会自动打开了,你就可以从当前位置直接飞进大门了。
注意:瓷砖可以重复走过,但不能重复计数。
输入格式
第一行两个正整数 W 和 H,分别表示小路的宽度和长度。
以下 H 行为一个 H×W 的字符矩阵。每一个字符代表一块瓷砖。其中,. 代表安全的砖,# 代表不安全的砖,@ 代表第一块砖。
输出格式
输出一行,只包括一个数,即你从第一块砖开始所能安全走过的最多的砖块个数(包括第一块砖)。
输入输出样例
输入 #1
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.
…
输出 #1
59
说明/提示
数据规模与约定
对于全部的测试点,保证 1≤W,H≤20。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cstdio>
#include<math.h>
#include <map>
using namespace std;
//#include <bits/stdc++.h>
//using namespace std;
//typedef long long ll;
int n,m,ans = 0,x = 0,y = 0;
char a[22][22];
int b[] = {0,0,0,1,-1};
int c[] = {0,1,-1,0,0};
int flag[22][22];
void search(int x1,int y1) {
for(int i = 1; i <= 4 ; i++) {
int dx = x1+b[i],dy = y1+c[i];
if(flag[dx][dy]==0&& dx> 0&&dx<= n&&dy>0&&dy<=m&&a[dx][dy]=='.' ) {
flag[dx][dy] = 1;
ans++;
search(dx,dy);
}
}
}
int main(){
cin>>m>>n;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> a[i][j];
if(a[i][j] == '@' ) {
x = i;
y = j;
}
}
}
ans++;
flag[x][y] = 1;
search(x,y);
cout << ans;
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<iomanip>
#include<algorithm>//喜欢多加几个头文件
using namespace std;
int n,m;
int ans=0;//答案
char a[21][21];//字符矩阵
bool b[21][21];//标志数组
inline void dfs(int x,int y)//dfs
{
if (x<1||x>m||y<1||y>n||a[x][y]=='#'|b[x][y]==false) return;//判断是否越界
b[x][y]=false;//false表示该点走过了
ans++;//答案加一
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);//向四个方向搜索
}
------------
真正的主程序从这里开始
int main()
{
ios::sync_with_stdio(false);//加快读入速度
cin>>n>>m;
int p,q;//用来记录@,起点
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++)
{
cin>>a[i][j];//读入
b[i][j]=true;//一开始都可以走
if (a[i][j]=='@') {p=i; q=j;}
}
dfs(p,q);//深搜
cout<<ans;//完美输出答案
return 0;
}