- Trending Categories
- 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++ code to find the number of scans needed to find an object

Suppose, we are given a grid of dimensions m x n. An object is placed at cell (ix, iy) and we have to find the object scanning from a starting position (sx, sy). The scanning algorithm scans the ith row and the j-th column of the grid if it is located at cell (i, j) of the grid. If it has found the object, the scanning stops; if not, the scanning pointer moves to cell in position (i + 1, j + 1) and then scans in the same way. This continues until the item is found. Given the positions, we have to find out how many scans the algorithm has to perform to find the object.

So, if the input is like n = 20, m = 20, sx = 3, sy = 2 , ix = 12, iy = 4, then the output will be 2.

## Steps

To solve this, we will follow these steps −

t1 := (if sx <= ix, then ix - sx, otherwise 2 * n - ix - sx) t2 := (if sy <= iy, then iy - sy, otherwise 2 * m - iy - sy) print(minimum of (t1, t2))

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; #define N 100 void solve(int n, int m, int sx, int sy, int ix, int iy) { int t1 = (sx <= ix ? ix - sx : 2 * n - ix - sx); int t2 = (sy <= iy ? iy - sy : 2 * m - iy - sy); cout<< min(t1, t2); } int main() { int n = 20, m = 20, sx = 3, sy = 2 , ix = 12, iy = 4; solve(n, m, sx, sy, ix, iy); return 0; }

## Input

20, 20, 3, 2 , 12, 4

## Output

2