迷失之牙(java)

在這裏插入圖片描述
樣例輸入:

5 6
1 1 0 0 0 1
1 0 1 0 0 1
0 1 0 1 0 0
1 1 1 0 0 1
1 1 1 1 1 1
3
0 0
4 5
2
0 0
4 5
3
3 5
3 0
0

樣例輸出:

true
false
true

ac代碼(附註釋):

package 迷失之牙;
import java.util.Scanner;

public class Main {
	Scanner sc = new Scanner(System.in);

	int n = 0;
	int m = 0;
	
	// 終點(end)座標
	int ex = 0; 
	int ey = 0;

	int[][] map; //迷宮數組

	boolean canSolve;

	public Main() {

		n = sc.nextInt();
		m = sc.nextInt();

		map = new int[n][m];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				map[i][j] = sc.nextInt();
			}
		}

		while(sc.hasNext()) {

			int p = sc.nextInt(); //power能量
			if(p==0) break;
			
			canSolve = false;
			
			// 起點(start)座標
			int sx = sc.nextInt();
			int sy = sc.nextInt();
			ex = sc.nextInt();
			ey = sc.nextInt();

			enterMaze(sx, sy, p);

			if (canSolve) {
				System.out.println(true);
			} else {
				System.out.println(false);
			}

		}
	}

	public static void main(String[] args) {
		new Main();
	}

	void enterMaze(int x, int y, int energy) {

		if (energy < 0 || x < 0 || y < 0 || x >= n || y >= m || map[x][y] == -1) {  
			return;
		} else {
			int temp = map[x][y]; // 局部變量!!!
			map[x][y] = -1; //起點以及走過的位置標記爲-1

			if (x == ex && y == ey) {
				map[x][y] = temp; // 測試多組數據 結果爲true或者false都要將標記爲-1的位置的能量賦值回去
				canSolve = true;
				return;
			}

			// 向上
			if(x-1>=0)
			enterMaze(x - 1, y, energy - map[x-1][y]);
			// 向右
			if(y + 1<m)
			enterMaze(x, y + 1, energy - map[x][y+1]);
			// 向下
			if(x+1<n)
			enterMaze(x + 1, y, energy - map[x+1][y]);
			// 向左
			if(y-1>=0)
			enterMaze(x, y - 1, energy - map[x][y-1]);

			map[x][y] = temp;
		}
	}

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