由于才学习算法,dfs这道题做了很久 便想把此写下来,留个纪念嘛
给一个 n 行 m 列的 2 维的迷宫,'S'
表示迷宫额起点,'T'
表示迷宫的终点,'#'
表示不能通过的点,'.'
表示可以通过的点。你需要从'S'
出发走到'T'
,每次只能上下左右走动,并且只能进入能通过的点,每个点只能通过一次。现在要求你求出有多少种通过迷宫的的方案。
输入格式
第一行输入 n, m (1≤n,m≤10) 表示迷宫大小。
接下来输入 n 行字符串表示迷宫。
输出格式
输入通过迷宫的方法数。
2 3 S.# ..T
2这道题算数dfs中最简单的一种了,,,,,,
下面是代码:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int ans =0;
int b [100][100];
char a [1000][1000];
int main(int argc, char *argv[])
{
int x1,y1,x2,y2;
int n,m,i,j;
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]=='S')
{
x1 = i; y1= j;
}else if(a[i][j]=='T')
{
x2= i;
y2= j;
}
}
}
b[x1][y1]=1;
dfs(x1,y1,x2,y2,n,m);
printf("%d",ans);
return 0;
}
void dfs (int x1 ,int y1,int x2,int y2,int n,int m)
{
int i;
int tx ,ty;
if(x1==x2&&y2==y1)
{
ans++;
return ;
}
int xx[4] ={0,1,-1,0};
int yy[4]= {1,0,0,-1};
for(i=0;i<4;i++)
{
tx = x1+xx[i];
ty = y1+yy[i];
if(a[tx][ty]!='#'&&tx>=0&&tx<n&&ty>=0&&ty<m&&b[tx][ty]!=1)
{
b[tx][ty]=1;
dfs(tx,ty,x2,y2,n,m);
b[tx][ty]=0;
}
}
}
先记录下起始点的位置坐标,然后从起点开始走,然后判断下一个位置能否走,能的话就下个位置标为1,表示已经走过,然后dfs下一步,dfs完记住要把标志位撤销,=0,因为要回溯,最后到了终点就ans 方案数加1 再return,返回上一步