SDUT OJ 走迷宮(DFS)

Description
有一個mn格的迷宮(表示有m行、n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,輸入這mn個數據和起始點、結束點(起始點和結束點都是用兩個數據來描述的,分別表示這個點的行號和列號)。現在要你編程找出所有可行的道路,要求所走的路中沒有重複的點,走時只能是上下左右四個方向。如果一條路都不可行,則輸出相應信息(用-1表示無路)。
Input
第一行是兩個數m,n(1< m, n< 15),接下來是m行n列由1和0組成的數據,最後兩行是起始點和結束點。
Output
所有可行的路徑,輸出時按照左上右下的順序。描述一個點時用(x,y)的形式,除開始點外,其他的都要用“->”表示。如果沒有一條可行的路則輸出-1。
Sample
Input
5 4
1 1 0 0
1 1 1 1
0 1 1 0
1 1 0 1
1 1 1 1
1 1
5 4
Output
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)

代碼如下:

import java.util.Scanner;

public class Main {
	
	static int[][] a;
	static int count = 0;
	static int b2, e2, m, n;
	static int[] b = new int[100];
	static int[][] dir = {{0,-1},{-1,0},{0,1},{1,0}};  //左, 下,右,上

	static int flag = 0;
	
	
	public static void dfs(int x, int y, int count) {
		//到了終點
		if(x==b2 && y==e2) {
			flag = 1;
			for(int i=0; i<count; i+=2) {
				System.out.print("("+b[i]+","+b[i+1]+")->");
			}
			System.out.println("("+b2+","+e2+")");
			return;
		}
		
		//邊界條件
		if(x == 0||x == m+1 || y == n+1||y == 0 || a[x][y] == 0) return;
		
		//四個方向各走一次
		for(int i=0; i<4; i++) {
			a[x][y] = 0; //將遍歷方向置0
			b[count] = x;
			b[count+1] = y;
			dfs(x+dir[i][0], y+dir[i][1], count+2);
			a[x][y] = 1; //恢復
		}
	}
	
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		while(scan.hasNext()) {
			m = scan.nextInt();
			n = scan.nextInt();
			a = new int[m+1][n+1];
			
			for(int i=1; i<=m; i++) {
				for(int j=1; j<=n; j++) {
					a[i][j] = scan.nextInt();
				}
			}
			
			int b1, e1;
			b1 = scan.nextInt();
			e1 = scan.nextInt();
			b2 = scan.nextInt();
			e2 = scan.nextInt();
			
			dfs(b1, e1, 0);
			if(flag == 0) System.out.println("-1");
		}
		scan.close();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章