题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int xNum = 0;
public static int yNum = 0;
public static int[][] maze = null;
public static boolean findRoute = false;
public static List<String> findRouteList = null;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n = -3;
List<Node1> line = new LinkedList<>();
while (in.hasNextInt()) { // 注意 while 处理多个 case
n++;
int a = in.nextInt();
if (n == -2) {
yNum = a;
continue;
} else if (n == -1) {
xNum = a;
maze = new int[yNum][xNum];
n = -1;
continue;
}
int i = n % xNum;
int j = n / xNum;
init(i, j, a);
}
int i = 0, j = 0;
Node1 node1 = new Node1();
node1.num = 0;
node1.i = i;
node1.j = j;
setNode1(node1, i, j);
findRouteList.forEach(item -> {
System.out.println(item);
});
}
private static void init(int i, int j, int a) {
maze[j][i] = a;
}
private static boolean cross(int i, int j) {
if(i<0 || j<0 || i >= xNum || j >= yNum){
return false;
}
int a = maze[j][i];
if (a == 0) {
return true;
}
return false;
}
private static String getRoute(int i, int j) {
return "(" + j + "," + i + ")";
}
private static boolean setFindEndRoute(Node1 node1){
if(node1.i == xNum-1 && node1.j == yNum -1){
findRouteList = node1.route;
return true;
}
return false;
}
private static void setNode1(Node1 node1, int i, int j) {
if(node1.route.contains(getRoute(i,j))){
return;
}
node1.route.add(getRoute(i,j));
if(setFindEndRoute(node1)){
return;
}
hasNext(node1, i, j, -1, 0);
hasNext(node1, i, j, 1, 0);
hasNext(node1, i, j, 0, -1);
hasNext(node1, i, j, 0, 1);
}
private static void hasNext(Node1 node1, int i, int j, int moveX,
int moveY) {
int i1 = i + moveX;
int j1 = j + moveY;;
if (!cross(i1, j1)) {
return;
}
node1.hasNext = true;
Node1 next = new Node1();
next.num = node1.num +1;
next.i = i1;
next.j = j1;
node1.route.forEach(item -> {
next.route.add(item);
});
//next.route.add(getRoute(i1,j1));
if (moveX == -1 && moveY == 0) {
node1.nextLetft = next;
} else if (moveX == 1 && moveY == 0) {
node1.nextRight = next;
} else if (moveX == 0 && moveY == 1) {
node1.nextDown = next;
} else if (moveX == 0 && moveY == -1) {
node1.nextUp = next;
}
setNode1(next, i1, j1);
}
static class Node1 {
public int num;
public int i;
public int j;
public Node1 nextLetft = null;
public Node1 nextRight = null;
public Node1 nextUp = null;
public Node1 nextDown = null;
public boolean hasNext = false;
public List<String> route = new LinkedList<>();
}
}
解题思路和91有点像,解了一天也是有了个好的成果。
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记
