C++程序查找网格中是否存在模式
假设,我们给定一个n * n维度的网格。我们必须检测网格中是否存在交叉图案,如下所示:
#...# .#.#. ..#.. .#.#. #...#
网格只能包含“#”和“.”。我们必须检测模式并找出网格中存在多少种此类模式。网格和维度作为输入提供给我们。
问题类别
编程中的各种问题可以通过不同的技术来解决。要解决问题,我们必须首先设计一个算法,为此,我们必须详细研究特定问题。如果同一问题反复出现,则可以使用递归方法;或者,我们也可以使用迭代结构。if-else 和 switch case 等控制语句可用于控制程序中逻辑的流程。有效使用变量和数据结构提供了更简单的解决方案以及轻量级、低内存需求的程序。我们必须查看现有的编程技术,例如分治法、贪心算法、动态规划,并找出是否可以使用它们。这个问题可以通过一些基本逻辑或蛮力方法来解决。请遵循以下内容以更好地理解该方法。
因此,如果我们问题的输入类似于 n = 5,并且网格为:
#...# .#.#. ..#.. .#.#. #...#,
则输出将为 1。
步骤
为了解决这个问题,我们将遵循以下步骤:
count := 0 for initialize i := 1, when i < n - 1, update (increase i by 1), do: for initialize j := 1, when j < n - 1, update (increase j by 1), do: if grid[i, j] is same as '#' and grid[i - 1, j - 1] is same as '#' and grid[i - 1, j + 1] is same as '#' and grid[i + 1, j - 1] is same as '#' and grid[i + 1, j + 1] is same as '#', then: (increase count by 1) print(count)
示例
让我们看一下以下实现以获得更好的理解:
#include<bits/stdc++.h>
using namespace std;
void solve(int n, vector<string> grid) {
int count = 0;
for(int i = 1; i < n - 1; i++){
for(int j = 1; j < n - 1; j++){
if(grid[i][j] == '#' && grid[i - 1][j - 1] == '#' && grid[i - 1][j + 1] == '#' && grid[i + 1][j - 1] == '#' && grid[i + 1][j + 1] == '#')
count++;
}
}
cout<< count;
}
int main() {
int n = 5;
vector<string> grid = {"#...#", ".#.#.", "..#..", ".#.#.", "#...#"};
solve(n, grid);
return 0;
}输入
5, {"#...#", ".#.#.", "..#..", ".#.#.", "#...#"}输出
1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP