假设,我们有一个包含两种类型单元格的网格;黑细胞和白细胞。黑色单元格表示为“#”,白色单元格表示为“.”。网格以字符串数组形式提供给我们。现在,我们必须执行以下操作。
我们将每个白色单元格转换为黑色单元格,并与黑色单元格共享一侧。我们执行此操作,直到网格的每个单元格都变成黑色。
我们计算将网格的所有单元格转换为黑色所需的迭代次数。一开始的网格必须包含一个黑色单元格。
因此,如果输入类似于 h = 4, w = 4, grid = {“#…” , “.#..” , “….”, “…#”}
立即学习“C++免费学习笔记(深入)”;
#....#...... ...#
那么输出将为3。
需要3次迭代才能转换所有单元格为黑色。
步骤
为了解决这个问题,我们将按照以下步骤操作 –
Define an array dx of size: 4 containing := { 1, 0, - 1, 0 }Define an array dy of size: 4 containing := { 0, 1, 0, - 1 }Define one 2D array distanceDefine one queue q that contain integer pairsfor initialize i := 0, when i = h or cy = w, then: if distance[cx, cy] is same as -1, then: distance[cx, cy] := distance[first value of now, second value of now] + 1 insert one pair (cx, cy) into qans := 0for initialize i := 0, when i示例
让我们看下面的实现以获得更好的理解 −
#include using namespace std;void solve(int h, int w, vector grid){ int dx[4] = { 1, 0, -1, 0 }; int dy[4] = { 0, 1, 0, -1 }; vector> distance(h, vector(w, -1)); queue> q; for (int i = 0; i (i,j)); } } } while (!q.empty()) { auto now = q.front(); q.pop(); for (int dir = 0; dir = h || cy = w) continue; if (distance[cx][cy] == -1) { distance[cx][cy] = distance[now.first][now.second] + 1; q.push(pair (cx, cy)); } } } int ans = 0; for (int i = 0; i grid = {"#...", ".#.." , "....", "...#"}; solve(h, w, grid); return 0;}登录后复制
输入
4, 4, {"#...", ".#.." , "....", "...#"}登录后复制
输出
3登录后复制
以上就是C++程序以找出将所有单元格转换为黑色所需的迭代次数的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2587812.html