博客
关于我
leetcode------130. 被围绕的区域【1】
阅读量:203 次
发布时间:2019-02-28

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

为了解决这个问题,我们需要找到所有被 'X' 围绕的区域,并将这些区域内的 'O' 填充为 'X'。边界上的 'O' 不会被填充,因为它们无法被 'X' 围绕。

方法思路

我们可以使用广度优先搜索(BFS)来解决这个问题。具体步骤如下:

  • 标记边界的 'O':首先,我们标记所有位于矩阵边界的 'O',这些 'O' 不会被填充,因为它们无法被 'X' 围绕。
  • BFS 遍历:然后,我们从这些边界的 'O' 开始,使用 BFS 遍历所有与这些边界 'O' 相连的 'O'。这些 'O' 也不会被填充,因为它们可以逃脱到边界。
  • 填充内部 'O':剩下的未被访问过的内部 'O' 会被填充为 'X',因为它们无法逃脱到边界。
  • 解决代码

    #include 
    #include
    using namespace std;void solve(vector
    > &board) { int n = board.size(); if (n == 0) return; int m = board[0].size(); vector
    > visited(n, vector
    (m, false)); queue
    > q; // 初始化边界的'O' for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (i == 0 || i == n-1 || j == 0 || j == m-1) { if (board[i][j] == 'O') { visited[i][j] = true; q.push({i, j}); } } } } // 四个方向:上下左右 int dirs[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; while (!q.empty()) { auto current = q.front(); q.pop(); int x = current.first; int y = current.second; for (int d = 0; d < 4; ++d) { int nx = x + dirs[d][0]; int ny = y + dirs[d][1]; if (nx >= 0 && nx < n && ny >=0 && ny < m) { if (board[nx][ny] == 'O' && !visited[nx][ny]) { visited[nx][ny] = true; q.push({nx, ny}); } } } } // 填充内部未被访问的'O' for (int i=0; i

    代码解释

  • 初始化边界 'O':我们遍历矩阵的边界,标记所有 'O' 并将它们加入队列。
  • BFS 遍历:从队列中取出元素,检查其四个邻居。如果邻居是 'O' 且未被访问过,则标记并加入队列。
  • 填充内部 'O':遍历整个矩阵,未被访问过的内部 'O' 被填充为 'X'。
  • 这种方法确保了所有无法逃脱到边界的 'O' 被正确填充为 'X',同时边界上的 'O' 保持不变。

    转载地址:http://tnki.baihongyu.com/

    你可能感兴趣的文章
    Progress Kemp LoadMaster 远程命令执行漏洞复现(CVE-2024-1212)
    查看>>
    Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
    查看>>
    Project Euler 15 Lattice paths
    查看>>
    Project Euler 48 Self powers( 大数求余 )
    查看>>
    Project Euler Problem 12: Highly divisible triangular number
    查看>>
    ProjectEuler 2
    查看>>
    projection介绍及EPSG:4326和EPSG:3857的投射转换
    查看>>
    project打开文件时,显示无法识别此文件格式?
    查看>>
    Prometheus + Grafana on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>
    Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
    查看>>
    Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
    查看>>
    Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
    查看>>
    Prometheus 介绍
    查看>>
    Prometheus 安全配置详解
    查看>>
    prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
    查看>>