给一个board,上面有0 和1,1不可以走,0 可以走。任意给一个start一个end,让输出最短的步数。follow up输出路径。就是BFS
public int minsteps(int board[][], int starti, int startj, int endi, int endj) {
int dirs[][] = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int m = board.length;
int n = board[0].length;
boolean visited[][] = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>(); // bfs
queue.offer(new int[] { starti, startj });
visited[starti][startj] = true;
int level = 0;
while (!queue.isEmpty()) {
level++;
int count = queue.size();
for (int i = 0; i < count; i++) {
int[] node = queue.poll();
for (int[] dir : dirs) {
//决定四个方向
int x = node[0] + dir[0];
int y = node[1] + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != 1 && !visited[x][y]) {
if (x == endi && y == endj) {
return level;
}
queue.offer(new int[] { x, y });
visited[x][y] = true;
}
}
}
}
return -1;
}
public List<int[]> minpath(int board[][], int starti, int startj, int endi, int endj) {
int dirs[][] = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int m = board.length;
int n = board[0].length;
Map<Integer, Integer> parent = new HashMap<>(); // int[] cannot equals
boolean visited[][] = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>(); // bfs
queue.offer(new int[] { starti, startj });
visited[starti][startj] = true;
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = 0; i < count; i++) {
int[] node = queue.poll();
for (int[] dir : dirs) {
int x = node[0] + dir[0];
int y = node[1] + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != 1 && !visited[x][y]) {
queue.offer(new int[] { x, y });
visited[x][y] = true;
//编码,保存
parent.put(x * n + y, node[0] * n + node[1]);
if (x == endi && y == endj) {
LinkedList<int[]> ret = new LinkedList<>();
while (x * n + y != starti * n + startj) {
ret.offerFirst(new int[] { x, y });
int p = parent.get(x * n + y);
x = p / n;
y = p % n;
}
return ret;
}
}
}
}
}
return null;
}
public static void main(String[] args) {
MinPath s = new MinPath();
System.out.println(s.minsteps(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1,
1, 1));
System.out.println(s.minsteps(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1,
2, 1));
System.out.println(s.minsteps(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1,
2, 2));
System.out.println();
System.out.println(s.minpath(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1,
1, 1));
for (int[] t : s.minpath(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1, 2, 1))
System.out.print("(" + t[0] + "," + t[1] + ") ");
System.out.println();
for (int[] t : s.minpath(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 0, 1, 2, 2))
System.out.print("(" + t[0] + "," + t[1] + ") ");
System.out.println();
}