C++ Program to find out if there is a pattern in a grid

Suppose, we are given a grid of dimensions n * n. We have to detect if there is a cross pattern in the grid, like below −

#...#
.#.#.
..#..
.#.#.
#...#

The grid can only contain '#' and '.'. We have to detect the pattern and find out how many such patterns are in the grid. The grid and the dimension are given to us as input.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first, and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can be used. This problem can be solved by some basic logic or a brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like n = 5, and grid =

#...#
.#.#.
..#..
.#.#.
#...#,

then the output will be 1.

Steps

To solve this, we will follow these steps −

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)

Example

Let us see the following implementation to get better understanding −

#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;
}

Input

5, {"#...#", ".#.#.", "..#..", ".#.#.", "#...#"}

1