C++ Program to find out the number of sides that a polygon has inside a grid

C++Server Side ProgrammingProgramming

Suppose, we are given a grid of dimensions h x w. There are two types of cells in the grid, white and black cells. White cells are represented by '.', whereas black cells are represented by '#'. Now the grid has multiple black cells in it that form a polygon. We have to find out the number of sides that the polygon has. It is to be noted, that the outermost cells of the grid are always white.

So, if the input is like h = 4, w = 4, grid = {"....", ".##.", ".##.", "...."}, then the output will be 4.

The black cells form a square, and a square has 4 sides.

Steps

To solve this, we will follow these steps −

sides := 0
for initialize i := 1, when i < h, update (increase i by 1), do:
   for initialize j := 1, when j < w, update (increase j by 1), do:
      bl := 0
      if grid[i - 1, j - 1] is same as '#', then:
         (increase bl by 1)
      if grid[i - 1, j] is same as '#', then:
         (increase bl by 1)
      if grid[i, j - 1] is same as '#', then:
         (increase bl by 1)
      if grid[i, j] is same as '#', then:
         (increase bl by 1)
      if bl is same as 1 or 3, then:
         (increase sides by 1)
return sides

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int h, int w, vector<string> grid){
   int sides = 0;
   for(int i = 1; i < h; i++) {
      for(int j = 1; j < w; j++) {
         int bl = 0;
         if(grid.at(i - 1).at(j - 1) == '#') {
            bl++;
         }
         if(grid.at(i - 1).at(j) == '#') {
            bl++;
         }
         if(grid.at(i).at(j - 1) == '#') {
            bl++;
         }
         if(grid.at(i).at(j) == '#') {
            bl++;
         }
         if(bl == 1 or bl == 3) {
            sides++;
         }
      }
   }
   cout << sides;
}
int main() {
   int h = 4, w = 4;
   vector<string> grid = {"....", ".##.", ".##.", "...."};
   solve(h, w, grid);
   return 0;
}

Input

4, 4, {"....", ".##.", ".##.", "...."}

Output

4
raja
Updated on 02-Mar-2022 12:55:32

Advertisements