博客
关于我
【纪中2020.2.19日】模拟赛题解
阅读量:323 次
发布时间:2019-03-03

本文共 1852 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要判断给定的地图是否存在死胡同。死胡同的定义是,从任意一个路面单元格出发,沿着任何一个可行的方向,都能返回到起点而不需要掉头。因此,我们需要检测地图中是否存在环路。

方法思路

我们可以使用广度优先搜索(BFS)来检测是否存在环路。具体步骤如下:

  • 遍历地图中的每个路面单元格。
  • 对于每个路面单元格,使用BFS进行深度优先搜索,检查是否存在环路。
  • 如果在BFS过程中发现一个单元格已经被访问过并且不是当前单元格的父节点,则说明存在环路。
  • 如果存在至少一个环路,则地图有死胡同,输出1;否则输出0。
  • 解决代码

    #include 
    #include
    using namespace std;bool has_cycle(int R, int C, char grid[R+1][C+1], int i, int j, vector
    >& parent, vector
    & visited) { queue
    > q; visited[i][j] = true; q.push({i, j}); parent[i][j] = make_pair(-1, -1); int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; while (!q.empty()) { auto curr = q.front(); q.pop(); int x = curr.first; int y = curr.second; for (int k = 0; k < 4; ++k) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx < 1 || nx > R || ny < 1 || ny > C) continue; if (grid[nx][ny] != '.') continue; if (!visited[nx][ny]) { visited[nx][ny] = true; parent[nx][ny] = make_pair(x, y); q.push({nx, ny}); } else { if (parent[x][y].first != nx || parent[x][y].second != ny) { return true; } } } } return false;}int main() { freopen("okret.in", "r", stdin); freopen("okret.out", "w", stdout); int R, C; scanf("%d %d", &R, &C); char grid[R+1][C+1]; for (int i = 1; i <= R; ++i) { scanf(" %c", &grid[i][1]); for (int j = 2; j <= C; ++j) { scanf(" %c", &grid[i][j]); } } vector
    visited(R+2, false); vector
    > parent(R+2, make_pair(-1, -1)); bool f = true; for (int i = 1; i <= R; ++i) { for (int j = 1; j <= C; ++j) { if (grid[i][j] == '.') { if (!has_cycle(R, C, grid, i, j, parent, visited)) { continue; } else { f = false; break; } } } if (!f) break; } if (f) { cout << 0; } else { cout << 1; }}

    代码解释

  • 读取输入:读取地图的大小R和C,然后读取地图数据。
  • 初始化数组:创建两个数组visitedparent来记录单元格的访问状态和父节点。
  • 遍历每个单元格:对于每个路面单元格,调用BFS函数进行环路检测。
  • BFS函数:从当前单元格出发,进行BFS,检查是否存在环路。如果存在环路,返回True。
  • 判断结果:如果存在环路,输出1,否则输出0。
  • 转载地址:http://dcim.baihongyu.com/

    你可能感兴趣的文章
    Postman还能做Mock?又学了一招!
    查看>>
    Postman还能做Mock?又学了一招!
    查看>>
    postman进行http接口测试
    查看>>
    Postman高阶技能:Collection集合批量运行!
    查看>>
    postMessage跨标签页共享数据
    查看>>
    QImage对一般图像的处理
    查看>>
    post为什么会发送两次请求?
    查看>>
    Post表单提交TextArea的值出现转译乱码问题 - Spring MVC处理表单提交
    查看>>
    Power BI 中的 Python 可视化需要什么设置?任何特定的 matplotlib 包版本或系统设置?
    查看>>
    Power BI:如何在 Power Query 编辑器中将 Python 与多个表一起使用?
    查看>>
    power english (3) main text -emotion mastery - focus
    查看>>
    POWER ENGLISH (6) - MODEL
    查看>>
    power english (1) —— passion
    查看>>
    Power English (1) 原文
    查看>>
    power English (3)原文
    查看>>
    POWER ENGLISH(7)- repetition
    查看>>
    SpringBoot中集成SpringBatch详细解析与实战示例(CSV文件读取十万条数据进行业务处理后写入Mysql数据库)
    查看>>
    powerbi 一张表在另外一张表中出现的数量_PowerBi之初步学习笔记
    查看>>
    QGIS怎样设置简体中文以及新建可编辑的多边形的图层
    查看>>
    PowerBuilder 使用自定义事件触发键盘Enter事件
    查看>>