一道入门图搜索算法题

DFS:

c 复制代码
#include <stdio.h>

#define MAX 25          // 题目最大 20,留一点余量
int W, H;               // 列数、行数
char grid[MAX][MAX];    // 地图
int visited[MAX][MAX];  // 访问标记,0 未访问,1 已访问
int cnt;                // 能到达的黑色砖块总数

// 四个方向:上、下、左、右
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

// 深度优先搜索
void dfs(int x, int y) {
    int i;
    for (i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        // 边界检查
        if (nx < 0 || nx >= H || ny < 0 || ny >= W) continue;
        // 只走黑色砖且未访问过
        if (grid[nx][ny] == '#' || visited[nx][ny]) continue;
        visited[nx][ny] = 1;
        cnt++;
        dfs(nx, ny);
    }
}

int main() {
    int i, j;
    int sx = 0, sy = 0;  // 起点坐标
    while (scanf("%d %d", &W, &H) == 2) {
        if (W == 0 && H == 0) break;  
        getchar();  // 吃掉行尾换行
        // 读地图
        for (i = 0; i < H; i++) {
            scanf("%s", grid[i]);
            for (j = 0; j < W; j++) {
                visited[i][j] = 0;
                if (grid[i][j] == '@') {
                    sx = i;
                    sy = j;
                }
            }
        }
        // 初始化
        cnt = 1;
        visited[sx][sy] = 1;
        // 从起点开始 DFS
        dfs(sx, sy);
        printf("%d\n", cnt);
    }
    return 0;
}

BFS:

c 复制代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

#define MAX 25

int W, H;
char g[MAX][MAX];
int vis[MAX][MAX];

int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

struct Point {
    int x, y;
};

int bfs(int sx, int sy) {
    int cnt = 1;
    queue<Point> q;
    q.push({sx, sy});
    vis[sx][sy] = 1;

    while (!q.empty()) {
        Point cur = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = cur.x + dx[i];
            int ny = cur.y + dy[i];
            if (nx < 0 || nx >= H || ny < 0 || ny >= W) continue;
            if (g[nx][ny] == '#' || vis[nx][ny]) continue;
            vis[nx][ny] = 1;
            cnt++;
            q.push({nx, ny});
        }
    }
    return cnt;
}

int main() {
    int sx, sy;
    while (cin >> W >> H && (W || H)) {
        for (int i = 0; i < H; i++) {
            cin >> g[i];
            for (int j = 0; j < W; j++)
                if (g[i][j] == '@') { 
                    sx = i; 
                    sy = j; 
                }
        }
        // 清空 vis
        memset(vis, 0, sizeof(vis));
        cout << bfs(sx, sy) << endl;
    }
    return 0;
}
相关推荐
scx201310041 天前
20260129LCA总结
算法·深度优先·图论
木井巳2 天前
【递归算法】验证二叉搜索树
java·算法·leetcode·深度优先·剪枝
山峰哥2 天前
SQL调优实战密码:索引策略与Explain工具深度破局之道
java·开发语言·数据库·sql·编辑器·深度优先
木井巳3 天前
【递归算法】二叉树剪枝
java·算法·leetcode·深度优先·剪枝
平生不喜凡桃李3 天前
LeetCode:路径总和 III
算法·leetcode·深度优先
广州浩能科技3 天前
好用的广州太赫兹足疗仪哪个厂家好
广度优先
Sarvartha3 天前
图论基础与遍历算法(BFS+DFS)
算法·深度优先
苦藤新鸡3 天前
49.二叉树的最大路径和
数据结构·算法·深度优先
2501_946961473 天前
AI 生成个人简历 PPT 定制化模板直接用
深度优先
不穿格子的程序员3 天前
从零开始写算法——图论篇2:课程表 + 实现前缀树(26叉树)
算法·深度优先·图论·dfs·bfs