題目描述:
小信是一個玩迷宮的高手,天下還沒有能難住他的迷宮。但是總有人喜歡刁難小信,不停的給小信出難題。這個出題的人很聰敏,他知道天下還沒有能難住小信的迷宮。所以他便轉換思維問小信,在不走重複路徑的情況下,總共有多少不同可以到達終點的路徑呢?小信稍加思索便給出了答案,你要不要也來挑戰一下?
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;
}