贪吃蛇bfs算法java代码
时间: 2024-04-02 12:28:38 浏览: 141
贪吃蛇游戏是一个经典的游戏,BFS算法可以用来实现贪吃蛇的自动寻路功能。下面是一个简单的贪吃蛇BFS算法的Java代码示例:
```java
import java.util.*;
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class SnakeGame {
private int[][] grid;
private int width;
private int height;
private int[] dx = {-1, 0, 1, 0}; // 上、右、下、左
private int[] dy = {0, 1, 0, -1};
public SnakeGame(int width, int height) {
this.width = width;
this.height = height;
this.grid = new int[width][height];
}
public int bfs(Point start, Point target) {
Queue<Point> queue = new LinkedList<>();
boolean[][] visited = new boolean[width][height];
queue.offer(start);
visited[start.x][start.y] = true;
int steps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Point curr = queue.poll();
if (curr.x == target.x && curr.y == target.y) {
return steps;
}
for (int j = 0; j < 4; j++) {
int newX = curr.x + dx[j];
int newY = curr.y + dy[j];
if (newX >= 0 && newX < width && newY >= 0 && newY < height && !visited[newX][newY]) {
queue.offer(new Point(newX, newY));
visited[newX][newY] = true;
}
}
}
steps++;
}
return -1; // 如果无法到达目标点,返回-1
}
public static void main(String[] args) {
int width = 10;
int height = 10;
SnakeGame game = new SnakeGame(width, height);
Point start = new Point(0, 0);
Point target = new Point(9, 9);
int steps = game.bfs(start, target);
if (steps == -1) {
System.out.println("无法到达目标点");
} else {
System.out.println("到达目标点的最短步数为:" + steps);
}
}
}
```
这段代码实现了一个简单的贪吃蛇游戏,并使用BFS算法寻找从起点到目标点的最短路径。在代码中,`bfs`方法使用队列来进行广度优先搜索,`visited`数组用于记录已经访问过的点,`steps`变量用于记录步数。最后,在`main`方法中创建了一个SnakeGame对象,并调用`bfs`方法来计算最短步数。
阅读全文