题目链接:迷宫 - 洛谷
思路
根据递归的特性,变化参数(变化位置),每到一个点就根据下右上左的方式去判断此路是否是通的,如果可以(只要其中有一个方位的位置的通的就算跑通了)跑通就在当前点在进行四个位置的搜索。当跑出界外无路可走的时候,就返回上一个点(进行下一个位置判断是否通,把当前跑通点设置为没有被走过,方便下一次从别的地方到这个点)
小坑
根据1≤N,M≤5我们可以知道地图大概的范围是5以上。
注意入口位置不是边界位置,障碍物不能走。
dfs(int x, int y){
//...
dfs(x+dx[i],y+dy[i]);
//...
vis[x][y]
}
AC代码
import java.util.Scanner;
public class Main {
public static int[][] matrix=new int[6][6]; //迷宫的位置
public static boolean[][] vis=new boolean[6][6];//是否访问的标志
public static int sum=0;
public static int dx[]={1,0,-1,0};
public static int dy[]={0,1,0,-1};
public static int sx = 0,sy = 0;
public static int fx = 0,fy = 0;
public static int a = 0,b = 0;
public static int n = 0,m = 0;
public static void dfs(int x,int y){
// System.out.println("("+x+","+y+")");
// System.out.println("fx="+fx+", fy="+fy);
if(x==fx && y==fy)
{
sum++;
return;
}
else {
for (int i = 0; i <4 ; i++) {
int newx =x+dx[i];
int newy =y+dy[i];
// if() newx newy不能越界 不能是阻碍物 不是访问过的
//只是说入口在sx,sy 不是边界条件在入口
if((newx >= 1 && newx <= n && newy >= 1 && newy <= m ) && !vis[newx][newy] && matrix[newx][newy] == 0){
// System.out.println("("+newx+","+newy+")");
vis[x][y]=true;
dfs(newx,newy);
vis[x][y]=false;
}
}
// System.out.println();
}
// System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
int t = sc.nextInt();
sx = sc.nextInt();
sy = sc.nextInt();
fx = sc.nextInt();
fy = sc.nextInt();
for (int i = 1; i <=n ; i++) {
for(int j = 1; j<=m; j++){
matrix[i][j] = 0;
}
}
for (int k = 1; k <= t ; k++) {
a = sc.nextInt();
b = sc.nextInt();
matrix[a][b] = 1;
}
dfs(sx,sy);
System.out.println(sum);
}
}
总结
只要动脑子,没有解决不了的事情