迷宫问题(dfs)

题目:

给一个 n 行 m 列的 2 维的迷宫,’S’表示迷宫额起点,’T’表示迷宫的终点,’#’表示不能通过的点,’.’ 表示可以通过的点。你需要从’S’出发走到’T’,每次只能上下左右走动,并且只能进入能通过的点,每个点只能通过一次。现在要求你求出有多少种通过迷宫的的方案。

輸入:

第一行输入 nnm(1n,m10) 表示迷宫大小

接下来输入 nn 行字符串表示迷宫

输出:通过迷宫的方法

输入:

2 3
S.#
..T

输出: 2

输入:

3 3
S..
.#.
..T

输出:2

import java.util.*;
//import java.io.*; 
public class Main {
	 static int ans,n,m;
	 static String mat[]=new String[11];
	 static int dir[][]= {{1,0},{0,1},{-1,0},{0,-1}};//对应的上下左右4各方向  
	 static boolean [][]visited=new boolean[11][11];
	 
	 static void dfs(int x,int y)
	 {
		 visited[x][y]=true;
		 if(mat[x].charAt(y)=='T') {
			 ans++;
		    return ;
		 }
		 if(mat[x].charAt(y)=='#')
		 {
			 return ;
		 }
		 for(int i=0;i<dir.length;i++)
		 {
			 x=x+dir[i][0];
			 y=y+dir[i][1];
			 if((-1<x&&x<n)&&(-1<y&&y<m))
			 {
				 if(visited[x][y]==false)
				 {
					 visited[x][y]=true;
					 dfs(x,y);
					 visited[x][y]=false;//hui shuo
				
			 }
		 }
			 x=x-dir[i][0];//hui shuo
			 y=y-dir[i][1];
		 }
		 
		 
	 }
   public static void main(String args[])
   {
	   //BufferedReader sc = new BufferedReader (new InputStreamReader(System.in));  
	   Scanner sc=new Scanner(System.in);
	 //  int n=0,m=0;
	 n=sc.nextInt();
	 m=sc.nextInt();
	   for(int i=0;i<n;i++)
	   {
		   mat[i]=sc.next();//每一行当作字符串读入
	   }
	   int x=0,y=0;
	   for(int i=0;i<n;i++)
	   {
		   for(int j=0;j<m;j++)
		   {
			   if(mat[i].charAt(j)=='S')
			   { x=i;
			       y=j;
			   }
		   }
	   }
	    ans=0;
	   dfs(x,y);
	   System.out.println(ans);
	   
	   
   }
}
#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;
	 	}
	 }
	
	
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/qq_36294146/article/details/79190888
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞