C++ Program to find cell where next robbery is going to happen


Suppose we have a 2D matrix of characters of size n x m. Where '*' and '.' two types of characters are present. Only three '*'s are there, representing there are 3 robberies, and all other places are marked as '.'. A detective got an information that the fourth robbery will be committed in such cell, that all four robbed cells will form the vertices of some rectangle, parallel to the sides of the map. We have to find the cell.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading. This problem needs matrix to store the input and then matrix-based operations can be used to solve this problem

https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

https://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm

So, if the input of our problem is like

*.*
*..
...

then the output will be (2, 3)

Steps

To solve this, we will follow these steps −

n := row count of matrix
m := column count of matrix
x := 0
y := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   for initialize j := 0, when j < m, update (increase j by 1), do:
      if matrix[i, j] is same as '*', then:
         x := x XOR i
         y := y XOR j
print (x + 1, y + 1)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<vector<char>> matrix){
   int n = matrix.size();
   int m = matrix[0].size();
   int x, y;
   x = y = 0;
   for (int i = 0; i < n; i++){
      for (int j = 0; j < m; j++)
         if (matrix[i][j] == '*'){
            x ^= i;
            y ^= j;
         }
   }
   cout << x + 1 << ", " << y + 1 << endl;
}
int main(){
   vector<vector<char>> matrix = { { '*', '.', '*' }, { '*', '.', '.' }, { '.', '.', '.' } };
   solve(matrix);
}

Input

{ { '*', '.', '*' }, { '*', '.', '.' }, { '.', '.', '.' } }

Output

2, 3

Updated on: 07-Apr-2022

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements