HJ43迷宫问题

image
示例1

输入:
5 5
0 1 0 0 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出:
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)

示例2

输入:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 1
0 1 1 1 0
0 0 0 0 0
输出:
(0,0)
(1,0)
(2,0)
(3,0)
(4,0)
(4,1)
(4,2)
(4,3)
(4,4)

答案如下:

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
	static int[][] direction = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
	static LinkedList<int[]> result = new LinkedList<int[]>();
	static int[][] matrix = null;

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		// 注意 hasNext 和 hasNextLine 的区别
		while (in.hasNextInt()) { // 注意 while 处理多个 case
			int row = in.nextInt();
			int column = in.nextInt();

			matrix = new int[row][column];
			for (int i = 0; i < row; i++) {
				for (int j = 0; j < column; j++) {
					matrix[i][j] = in.nextInt();
				}
			}
			dfs(0, 0);

			for (int[] ints : result) {
				System.out.println("(" + ints[0] + "," + ints[1] + ")");
			}
		}


	}

	public static boolean dfs(int i, int j) {
		//将走过的路径添加到集合中,并且标记走过的路径
		result.add(new int[]{i, j});
		matrix[i][j] = 1;

		if (i == matrix.length - 1 && j == matrix[0].length - 1) {
			return true;
		}
		//向下查找
		if (i + 1 >= 0 && j >= 0 && i + 1 < matrix.length && j < matrix[0].length && matrix[i + 1][j] == 0) {
			if (dfs(i + 1, j)) {
				return true;
			}
		}
		//向右查找
		if (i >= 0 && j + 1 >= 0 && i < matrix.length && j + 1 < matrix[0].length && matrix[i][j + 1] == 0) {
			if (dfs(i, j + 1)) {
				return true;
			}
		}
		//向上查找
		if (i - 1 >= 0 && j >= 0 && i - 1 < matrix.length && j < matrix[0].length && matrix[i - 1][j] == 0) {
			if (dfs(i - 1, j)) {
				return true;
			}
		}
		//向左查找
		if (i >= 0 && j - 1 >= 0 && i < matrix.length && j - 1 < matrix[0].length && matrix[i][j - 1] == 0) {
			if (dfs(i, j - 1)) {
				return true;
			}
		}
		//回溯
		result.removeLast();
		matrix[i][j] = 0;//将走过的路径重新标记为没有走过
		return false;
	}
}
posted @ 2026-06-30 12:04  Carey_ccl  阅读(7)  评论(0)    收藏  举报