迷宫
题目描述
给定一个 N × M N \times M N×M 方格的迷宫,迷宫里有 T T T 处障碍,障碍处不可通过。
在迷宫中移动有上下左右四种方式,每次只能移动一个方格。数据保证起点上没有障碍。
给定起点坐标和终点坐标,每个方格最多经过一次,问有多少种从起点坐标到终点坐标的方案。
输入格式
第一行为三个正整数 N , M , T N,M,T N,M,T,分别表示迷宫的长宽和障碍总数。
第二行为四个正整数 S X , S Y , F X , F Y SX,SY,FX,FY SX,SY,FX,FY, S X , S Y SX,SY SX,SY 代表起点坐标, F X , F Y FX,FY FX,FY 代表终点坐标。
接下来 T T T 行,每行两个正整数,表示障碍点的坐标。
输出格式
输出从起点坐标到终点坐标的方案总数。
样例 #1
样例输入 #1
2 2 1
1 1 2 2
1 2
样例输出 #1
1
提示
对于 100 % 100\% 100% 的数据, 1 ≤ N , M ≤ 5 1 \le N,M \le 5 1≤N,M≤5, 1 ≤ T ≤ 10 1 \le T \le 10 1≤T≤10, 1 ≤ S X , F X ≤ n 1 \le SX,FX \le n 1≤SX,FX≤n, 1 ≤ S Y , F Y ≤ m 1 \le SY,FY \le m 1≤SY,FY≤m。
import java.util.Scanner;
public class Main {
static int N = 10;
static int g[][] = new int[N][N];
static boolean st[][] = new boolean[N][N];
static int cnt;
static int n, m, t;
static int sx, sy, fx, fy;
static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
t = sc.nextInt();
sx = sc.nextInt(); sy = sc.nextInt();
fx = sc.nextInt(); fy = sc.nextInt();
while(t-- != 0) {
int x = sc.nextInt(), y = sc.nextInt();
g[x][y] = 1;
}
dfs(sx, sy);
System.out.println(cnt);
sc.close();
}
public static void dfs(int tx, int ty) {
if(tx == fx && ty == fy) {
cnt++;
return;
}
// 进来就访问它
st[tx][ty] = true;
for(int i = 0; i < 4; i++) {
int x = tx + dx[i], y = ty + dy[i];
if(x < 1 || x > n || y < 1 || y > m) continue;
if(g[x][y] == 1 || st[x][y]) continue;
dfs(x, y);
st[x][y] = false; // 恢复现场
}
}
}