题目描述
给定一个 �×�N×M 方格的迷宫,迷宫里有 �T 处障碍,障碍处不可通过。
在迷宫中移动有上下左右四种方式,每次只能移动一个方格。数据保证起点上没有障碍。
给定起点坐标和终点坐标,每个方格最多经过一次,问有多少种从起点坐标到终点坐标的方案。
输入格式
第一行为三个正整数 N,M,T,分别表示迷宫的长宽和障碍总数。
第二行为四个正整数 SX,SY,FX,FY,SX,SY 代表起点坐标,FX,FY 代表终点坐标。
接下来 T 行,每行两个正整数,表示障碍点的坐标。
输出格式
输出从起点坐标到终点坐标的方案总数。
输入输出样例
输入 #1复制
2 2 1 1 1 2 2 1 2
输出 #1复制
1
import java.util.Scanner;
public class P1605 {
static int n,m,t,sx,sy,fx,fy,ans;
static boolean[][]visited = new boolean[20][20];
static boolean[][]barry = new boolean[20][20];//障碍
static int[]xx = {0,0,1,-1};
static int[]yy = {1,-1,0,0};
public static void main(String[] args) {
Scanner scan = new Scanner((System.in));
n = scan.nextInt();
m = scan.nextInt();
t = scan.nextInt();
sx = scan.nextInt();//起点
sy = scan.nextInt();
fx = scan.nextInt();//终点
fy = scan.nextInt();
for(int i=0;i<t;i++){
int a = scan.nextInt();
int b = scan.nextInt();
barry[a][b] = true;//设置障碍物
}
visited[sx][sy] = true;
dfs(sx,sy);
System.out.println(ans);
}
public static void dfs(int x,int y){
if(x==fx&&y==fy){
ans++;
return;
}
//上下左右搜索
for(int i=0;i<4;i++){
int dx = x+xx[i];
int dy = y+yy[i];
if(!visited[dx][dy]&&dx>=1&&dx<=n&&dy>=1&&dy<=m&&!barry[dx][dy]){
visited[dx][dy] = true;
dfs(dx,dy);
visited[dx][dy] = false;
}
}
}
}
(要把初始节点设置为访问过)