算法1 手写队列
时间比使用自定义内部类+Queue有微小提升。。。
import java.io.*;
class Main {
static int[][] g = new int[110][110];
static boolean[][] flag = new boolean[110][110];
static int[] queue = new int[10010];
static int[] ex = new int[10010];
static int[] ey = new int[10010];
static int[] eStep = new int[10010];
static int idx, head, tail;
static int n, m;
static int[] mx = {-1, 0, 1, 0};
static int[] my = {0, -1, 0, 1};
static void bfs() {
int x = 1, y = 1;
//x,y入队
ex[idx] = x;
ey[idx] = y;
eStep[idx] = 0;
queue[tail++] = idx++;
flag[x][y] = true;
while (head < tail) {
int e = queue[head++];
if (ex[e] == n && ey[e] == m) {
System.out.println(eStep[e]);
return;
}
for (int i = 0; i < 4; i++) {
x = ex[e] + mx[i];
y = ey[e] + my[i];
if (x > 0 && x <= n && y > 0 && y <= m && !flag[x][y] && g[x][y] == 0) {
flag[x][y] = true;
ex[idx] = x;
ey[idx] = y;
eStep[idx] = eStep[e] + 1;
queue[tail++] = idx++;
}
}
}
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
for (int i = 1; i <= n; i++) {
strs = in.readLine().split(" ");
for (int j = 1; j <= m; j++) g[i][j] = Integer.parseInt(strs[j - 1]);
}
bfs();
in.close();
isr.close();
}
}
算法2 使用自定义内部类+Queue
速度也很快。。。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
class Main {
static class Point {
int x, y, step;
public Point(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
static int[][] g = new int[110][110];
static boolean[][] flag = new boolean[110][110];
static Queue queue = new ArrayDeque<>();
static int n, m;
static int[] mx = {-1, 0, 1, 0};
static int[] my = {0, -1, 0, 1};
static void bfs() {
int x = 1, y = 1;
//x,y入队
queue.add(new Point(x, y, 0));
while (!queue.isEmpty()) {
Point p = queue.poll();
if (p.x == n && p.y == m) {
System.out.println(p.step);
return;
}
for (int i = 0; i < 4; i++) {
x = p.x + mx[i];
y = p.y + my[i];
if (x > 0 && x <= n && y > 0 && y <= m && !flag[x][y] && g[x][y] == 0) {
flag[x][y] = true;
queue.add(new Point(x, y, p.step + 1));
}
}
}
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
for (int i = 1; i <= n; i++) {
strs = in.readLine().split(" ");
for (int j = 1; j <= m; j++) g[i][j] = Integer.parseInt(strs[j - 1]);
}
bfs();
in.close();
isr.close();
}
}