import java.util.LinkedList;
import java.util.Queue;
public class Solution {
private static final int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public void bfs(char[][] grid, boolean[][] visited, int x, int y) {
int m = grid.length;
int n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{x, y});
visited[x][y] = true;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int curx = cur[0];
int cury = cur[1];
for (int i = 0; i < 4; i++) {
int nextx = curx + dir[i][0];
int nexty = cury + dir[i][1];
if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && !visited[nextx][nexty]) {
queue.add(new int[]{nextx, nexty});
visited[nextx][nexty] = true;
}
}
}
}
}
这是一个基于Java的BFS(广度优先搜索)模板代码,用于解决图论中的最短路径问题。以下是对代码的简要解释:
1. `bfs` 方法是实际进行广度优先搜索的函数。它接受一个字符类型的二维数组 `grid`,一个布尔类型的二维数组 `visited` 用于标记是否已经访问过某个位置,以及起始点的坐标 `(x, y)`。
2. `dir` 数组定义了四个方向:上、右、下、左。用于在搜索过程中移动。
3. 使用队列 `Queue` 存储待访问的节点。将起始点加入队列,并将其标记为已访问。
4. 在队列不为空的情况下,循环进行如下操作:
- 取出队列中的当前节点。
- 遍历当前节点的上、右、下、左四个相邻节点。
- 如果相邻节点在合法范围内且未被访问过,将其加入队列,并标记为已访问。
这个模板代码可以用于解决迷宫问题、岛屿数量问题等需要找到最短路径的场景。你可以在此基础上进行适当的修改来满足特定问题的需求。