栈实现DFS算法

该博客介绍了如何利用栈来实现DFS算法,以解决递归深度过深导致的爆栈问题。在二维网格中,算法遍历1表示的岛屿,计算其面积并更新最大面积,过程中将已访问节点压入栈中,并逐个检查相邻节点。这种方法有效地优化了传统递归DFS的性能。
摘要由CSDN通过智能技术生成

DFS是搜索算法中非常常见的一种算法,通常实现的时候会通过递归调用的方式来实现,但是众所周知,当递归深度很深时可能会出现爆栈的情况。

针对上述可能出现的问题,这里通过栈来实现DFS操作。

int dims[5] = { -1, 0, 1, 0, -1 };  //四个方向的实现。

stack<DIM> stack_dfs;  //定义栈结构,用于存储每次DFS的节点。

int grid_data[100][100];
int max_area = 0;
struct DIM {
    int x;
    int y;
};
// 定义坐标
int dims[5] = { -1, 0, 1, 0, -1 };
stack<DIM> stack_dfs;
void DFS(int row, int col) {
    if (grid_data[row][col] == 1) {
        int island_area = 1;
        DIM datas = { row, col };
        stack_dfs.emplace(datas);
        grid_data[row][col] = 0;
        while (!stack_dfs.empty()) {
            row = stack_dfs.top().x;
            col = stack_dfs.top().y;
            stack_dfs.pop();
            for (int i = 0; i < 4; i++) {
                int x = row + dims[i];
                int y = col + dims[i + 1];
                if (isValide(x, y) && grid_data[x][y] == 1) {
                    DIM datas = { x, y };
                    stack_dfs.emplace(datas);
                    grid_data[x][y] = 0;
                    ++island_area;
                }
            }
        }
        max_area = max(island_area, max_area);
    }
}
// 用于计算最大值,尽量使用内联函数,提高效率
inline int max(const int& a, const int& b) {
    if (a > b) return a;
    return b;
}

// 判断坐标是否有效
inline bool isValide(const int& x, const int& y) {
    if (x >= 0 && x < max_x && y <= 0 && y < max_y) {
        return true;
    }
    return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值