路径
问题描述
M*N的都是0,1,2的矩阵,M,N<=100,输出从初始位置(s_i,s_j)到最近的1的位置的路径,0能自由通行,1只能从上往下或者从下往上走到,2不能过。
同样距离的取行较小、同行再取列较小。
例:
3 4 1 1
(3行4列,初始位置第1行第1列)
0 0 0 0
2 1 0 1
0 0 0 0
输出 1 1 1 2 2 2,(1,1)->(1,2)->(2,2)
解题思路
- 新建队列并添加起始节点
- 创建M*N的矩阵,并初始化为false,表示元素未访问;
- 当队列不为空时,执行下述步骤
-
- 移除队列第一个元素,并标记元素为已访问
-
- 获取当前元素相临元素并检查是否已访问及是否能被访问
-
- 未访问的相临元素,计算并保存到开始节点的距离
-
- 若相临元素为1,停止查找并返回路径
-
- 若遍历完也未找到符合条件的元素,返回null
代码示例
static int[] row = {-1, 0, 1, 0}; // to traverse in all directions
static int[] col = {0, 1, 0, -1};
public static String findPath(int[][] matrix, int rowNo, int colNo) {
int x = rowNo - 1;
int y = colNo - 1;
int m = matrix.length;
int n = matrix[0].length;
Queue<int[]> q = new LinkedList<>();
boolean[][] visited = new boolean[m][n];
int[][] dist = new int[m][n]; // to store distance to source
// initialization
q.offer(new int[]{x, y});
visited[x][y] = true;
dist[x][y] = 0;
while (!q.isEmpty()) {
int[] curr = q.poll();
int currX = curr[0];
int currY = curr[1];
// check if current cell is 1
if (matrix[currX][currY] == 1) {
return getPath(dist, visited, x, y, currX, currY);
}
// traverse in all directions starting from current cell
for (int i = 0; i < 4; i++) {
int nextX = currX + row[i];
int nextY = currY + col[i];
// check if next cell is within bounds and unvisited
if (isValid(nextX, nextY, m, n) && !visited[nextX][nextY] && matrix[nextX][nextY] != 2) {
// update distance and add to queue
dist[nextX][nextY] = dist[currX][currY] + 1;
visited[nextX][nextY] = true;
q.offer(new int[]{nextX, nextY});
}
}
}
// there is no path to 1
return null;
}
private static boolean isValid(int x, int y, int m, int n) {
return x >= 0 && x < m && y >= 0 && y < n;
}
private static String getPath(int[][] dist, boolean[][] visited, int startX, int startY, int destX, int destY) {
List<String> list = new ArrayList<>();
// backtrack from destination to source using distance matrix
while (destX != startX || destY != startY) {
list.add(String.format("(%s,%s)", destX + 1, destY + 1));
int minDist = Integer.MAX_VALUE;
int nextX = -1;
int nextY = -1;
// get smallest distance neighbor
for (int i = 0; i < 4; i++) {
int adjX = destX + row[i];
int adjY = destY + col[i];
if (isValid(adjX, adjY, dist.length, dist[0].length) && visited[adjX][adjY] && dist[adjX][adjY] < minDist) {
minDist = dist[adjX][adjY];
nextX = adjX;
nextY = adjY;
}
}
destX = nextX;
destY = nextY;
}
list.add(String.format("(%s,%s)", startX + 1, startY + 1));
Collections.reverse(list);
// return reversed path
return list.stream().collect(Collectors.joining("->"));
}