- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to find out the number of border cells in a grid
Suppose, we are given a grid of dimensions h * w. We have to color the border cells of the grid (i.e. the outermost cells of the grid) with a special color. We have to find out how many border cells we have to color.
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 h = 4, w = 4, then the output will be 12.
Steps
To solve this, we will follow these steps −
return (2 * ((h - 2) + 2 * (w - 2)))
Example
Let us see the following implementation to get better understanding −
#include<bits/stdc++.h> using namespace std; void solve(int h, int w) { cout<< 2 * (h - 2) + 2 * (w - 2) + 4 ; } int main() { int h = 4, w = 4; solve(h, w); return 0; }
Input
4, 4
Output
12