题目描述:
小信是一个玩迷宫的高手,天下还没有能难住他的迷宫。但是总有人喜欢刁难小信,不停的给小信出难题。这个出题的人很聪敏,他知道天下还没有能难住小信的迷宫。所以他便转换思维问小信,在不走重复路径的情况下,总共有多少不同可以到达终点的路径呢?小信稍加思索便给出了答案,你要不要也来挑战一下?
Input
第一行输入两个整数 n(1 ≤ n ≤ 11), m(1 ≤ m ≤ 11).表示迷宫的行和列。
然后有一个 n × m 的地图,地图由’.’、’#’、‘s’、‘e’这四个部分组成。’.‘表示可以通行的路,’#'表示迷宫的墙,'s’表示起始点,'e’表示终点。
Output
输出一个整数,表示从’s’到达’e’的所有方案数。
Sample Input 1
5 5
s####
.####
.####
.####
…e
Sample Output 1
1
Sample Input 2
3 3
s…
…#
…e
Sample Output 2
7
解题思路:
深搜。搜到终点e的时候,就方案数+1.
AC代码:
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int start_x,start_y,end_x,end_y;
int n,m;
char map[105][105];//存储座标系
int vis[105][105];//存储该点是否被访问过
int ans;//方案的个数
bool in(int x,int y)
{
return x>=0&&x<n&&y>=0&&y<m;
}
void dfs(int x,int y)
{
if(!in(x,y)||vis[x][y]||map[x][y]=='#')
return ;
if(x==end_x&&y==end_y)
{
ans++;
return ;
}
vis[x][y]=1;
dfs(x,y+1);
dfs(x+1,y);
dfs(x,y-1);
dfs(x-1,y);
vis[x][y]=0;//注意这里,记得取消标记
}
int main()//'#'代表故宫的墙 ,'.'则表示可以通行,'s'代表起点,'e'代表终点
{
int i,j;
cin>>n>>m;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>map[i][j];
for(i=0;i<n;i++)//找到起点和终点的纵座标
{
for(j=0;j<m;j++)
{
if(map[i][j]=='s')
{
start_x=i;
start_y=j;
}
if(map[i][j]=='e')
{
end_x=i;
end_y=j;
}
}
}
dfs(start_x,start_y);//搜索的起点为s的横纵座标
cout<<ans<<endl;
return 0;
}