package test;
public class DFS {
final static int MAXN = 100;
static boolean vst[][] = new boolean[MAXN][MAXN];
static int dir[][] = new int[][] { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
static int map[][] = new int[MAXN][MAXN];
static void dfs(int x, int y) {
vst[x][y] = true;
if (map[x][y] == G) { //G为边界条件
return ;
}
for (int i = 0; i < 4; i++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if (checkEdge(tx, ty)) {
dfs(tx, ty);
}
}
}
static boolean checkEdge(int x,int y) {
if (!vst[x][y]) {
return true;
}
return false;
}
public static void main(String[] args) {
}
}
DFS深度优先搜索模板
最新推荐文章于 2025-06-07 10:27:59 发布
本文介绍了一个使用深度优先搜索(DFS)算法进行网格遍历的Java实现案例。该算法在一个二维数组表示的地图中进行搜索,并利用递归方式访问每个可达节点,避免重复访问已检查过的节点。文章详细展示了如何通过方向数组来控制上下左右四个方向的移动。
276

被折叠的 条评论
为什么被折叠?



