java 藍橋杯 走出迷宮
阿新 • • 發佈:2019-02-10
給一個 n 行 m 列的 2 維的迷宮,'S'表示迷宮額起點,'T'表示迷宮的終點,'#'表示不能通過的點,'.' 表示可以通過的點。你需要從'S'出發走到'T',每次只能上下左右走動,並且只能進入能通過的點,每個點只能通過一次。現在要求你求出有多少種通過迷宮的的方案。
輸入:
第一行輸入 nn, m (1≤n,m≤10) 表示迷宮大小
接下來輸入 nn 行字串表示迷宮
輸出:通過迷宮的方法
輸入:
2 3
S.#
..T
輸出: 2
輸入:
3 3
S..
.#.
..T
輸出:2
import java.util.*; public class Main { static boolean k[][]; //判斷是否走過 static String f[][]; static int dir[][]=new int[][]{{1,0},{0,1},{-1,0},{0,-1}}; //方向 static int q,w,count=0,x,y; public static void main(String args[]) { Scanner cn=new Scanner(System.in); q=cn.nextInt(); w=cn.nextInt(); k=new boolean[q][w]; f=new String[q][w]; for(int i=0;i<q;i++) { String str=cn.next(); for(int a=0;a<str.length();a++) { f[i][a]=""+str.charAt(a); if(f[i][a].equals("S")){x=i;y=a;k[i][a]=true;} if(f[i][a].equals("#")){k[i][a]=true;} //把障礙設定為true } } dd(x,y); System.out.println(count); } public static void dd(int x,int y) { if(f[x][y].equals("T")){ count++; return; } /* if(f[x][y].equals("#")) return;*/ for(int i=0;i<dir.length;i++) { x=x+dir[i][0]; y=y+dir[i][1]; if(x>=0&&x<q&&y>=0&&y<w&&k[x][y]==false) { k[x][y]=true; dd(x,y); k[x][y]=false; } x=x-dir[i][0]; y=y-dir[i][1]; } } }