题目:
代码:
package maze;
import java.util.LinkedList;
import java.util.Queue;
class Pos {
int x, y, step;
public Pos(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
public class T2 {
static int[][] maze = new int[20][20];
static Queue<Pos> q = new LinkedList<>();
static int[][] step = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static Queue<String> p = new LinkedList<>();
public static void main(String[] args) {
int ans = 0;
p.add("");
q.add(new Pos(9, 9, 0));
q.add(new Pos(0,0,0));
while (!q.isEmpty()) {
Pos pos = q.peek();
if (pos.step == 4) {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (maze[i][j] == 1)
ans++;
}
}
print_maze(maze);
System.out.println(ans);
return;
}
for (int i = 0; i < 4; i++) {
int x = pos.x + step[i][0];
int y = pos.y + step[i][2];
if (!check(x,y)) continue;
maze[x][y] = 1;
q.add(new Pos(x, y, pos.step + 1));
p.add(p.peek()+"("+x+","+y+")");
}
q.poll();
p.poll();
}
}
private static boolean check(int x, int y) {
return x>=0&&x< maze.length&&y>=0&&y< maze[0].length&&maze[x][y]==0;
}
private static void print_maze(int[][] maze) {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (maze[i][j]==1)
System.out.print("★ ");
else
System.out.print("□ ");
}
System.out.println();
}
}
}
运行结果: