📜  二维数组上的深度优先遍历 (DFS)(1)

📅  最后修改于: 2023-12-03 15:36:03.696000             🧑  作者: Mango

二维数组上的深度优先遍历 (DFS)

简介

深度优先遍历(Depth-First-Search,简称DFS)是一种计算机科学领域中的搜索算法。该算法沿着图的深度遍历图的节点,尽可能深地搜索图的分支。当节点v的所有边都被访问过后,搜索会回溯到节点v的前一个节点,继续深度优先搜索下一个分支。

在二维数组中,DFS算法可以用于寻找连通分量、寻找最短路径等问题。

实现
递归实现

Python实现

def dfs(grid, i, j):
    if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
        return
    grid[i][j] = 0
    dfs(grid, i-1, j)
    dfs(grid, i+1, j)
    dfs(grid, i, j-1)
    dfs(grid, i, j+1)

grid = [
    [1, 1, 0, 0, 0],
    [1, 1, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1]
]
count = 0
for i in range(len(grid)):
    for j in range(len(grid[0])):
        if grid[i][j] == 1:
            count += 1
            dfs(grid, i, j)
print(count)  # 输出连通块数量:3

Java实现

class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }

    public void dfs(char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
            return;
        }
        grid[i][j] = '0';
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
    }
}
栈实现

Python实现

def dfs(grid, i, j):
    stack = [(i, j)]
    while len(stack) > 0:
        i, j = stack.pop()
        if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
            continue
        grid[i][j] = 0
        stack.append((i-1, j))
        stack.append((i+1, j))
        stack.append((i, j-1))
        stack.append((i, j+1))

grid = [
    [1, 1, 0, 0, 0],
    [1, 1, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1]
]
count = 0
for i in range(len(grid)):
    for j in range(len(grid[0])):
        if grid[i][j] == 1:
            count += 1
            dfs(grid, i, j)
print(count)  # 输出连通块数量:3

Java实现

class Solution {
    public int numIslands(char[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        int count = 0;
        Stack<int[]> stack = new Stack<int[]>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    stack.push(new int[]{i, j});
                    while (!stack.isEmpty()) {
                        int[] cur = stack.pop();
                        int x = cur[0], y = cur[1];
                        if (x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == '1') {
                            grid[x][y] = '0';
                            stack.push(new int[]{x-1, y});
                            stack.push(new int[]{x+1, y});
                            stack.push(new int[]{x, y-1});
                            stack.push(new int[]{x, y+1});
                        }
                    }
                }
            }
        }
        return count;
    }
}
总结

二维数组上的深度优先遍历可以通过递归或栈实现,可以用于求连通分量、求最短路径等问题。注意边界问题,在使用栈实现时可以将遍历过的节点入栈,避免重复访问,同时使代码简洁易懂。