gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
现有n维迷宫有0和1随机组成,0表示通路,1表示障碍。入口坐标(0,0),出口坐标(n-1,…
- User
现有n维迷宫有0和1随机组成,0表示通路,1表示障碍。入口坐标(0,0),出口坐标(n-1, n-1),求入口到出口的最短路径,要求可以斜着走,并输出路径的坐标以及路径的长度。请用java语言编写完整代码
- Assistant
以下是使用Java编写的一个可能解决这个问题的算法:
import java.util.ArrayDeque; import java.util.Queue; public class Maze { static char[][] maze = { {'0', '1', '1', '1'}, {'0', '0', '0', '1'}, {'1', '0', '1', '1'}, {'1', '0', '0', '0'}, }; static int n = maze.length; static boolean[][] visited = new boolean[n][n]; static class Point { int x, y, steps; Point(int x, int y, int steps) { this.x = x; this.y = y; this.steps = steps; } } static int[] dx = {-1, 1, 0, 0, -1, -1, 1, 1}; static int[] dy = {0, 0, -1, 1, -1, 1, 1, -1}; static boolean isValid(int x, int y) { if (x >= 0 && x < n && y >= 0 && y < n && maze[x][y] == '0' && !visited[x][y]) { return true; } return false; } static int bfs() { Queue<Point> queue = new ArrayDeque<>(); queue.add(new Point(0, 0, 1)); visited[0][0] = true; while (!queue.isEmpty()) { Point cur = queue.poll(); if (cur.x == n - 1 && cur.y == n - 1) { return cur.steps; } for (int i = 0; i < dx.length; i++) { int newX = cur.x + dx[i]; int newY = cur.y + dy[i]; if (isValid(newX, newY)) { queue.add(new Point(newX, newY, cur.steps + 1)); visited[newX][newY] = true; } } } return -1; } public static void main(String[] args) { System.out.println("Shortest path length: " + bfs()); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.