一道入门图搜索算法题

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;
}
相关推荐
Elias不吃糖5 小时前
克隆图(LeetCode 133)——用数组做映射的 DFS 解法
c++·算法·leetcode·深度优先
CoderYanger6 小时前
递归、搜索与回溯-综合练习:28.不同路径Ⅲ
java·算法·leetcode·深度优先·1024程序员节
CoderYanger8 小时前
递归、搜索与回溯-综合练习:22.优美的排列
java·算法·leetcode·深度优先·1024程序员节
Elias不吃糖18 小时前
LeetCode--130被围绕的区域
数据结构·c++·算法·leetcode·深度优先
im_AMBER18 小时前
数据结构 12 图
数据结构·笔记·学习·算法·深度优先
啊董dong19 小时前
noi-11月30日当堂练习
算法·深度优先·图论
五花就是菜1 天前
P12906 [NERC 2020] Guide 题解
算法·深度优先·图论
Controller-Inversion2 天前
岛屿问题(dfs典型问题求解)
java·算法·深度优先
玖剹2 天前
递归练习题(四)
c语言·数据结构·c++·算法·leetcode·深度优先·深度优先遍历