VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-submatrix-which-holds-the-given-co-ordinate/

⇱ Find the Submatrix which holds the given co-ordinate - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Submatrix which holds the given co-ordinate

Last Updated : 19 Sep, 2022

Given a matrix mat of N*N (N is a perfect square|) and two points x and y, the task is to return all the elements of the submatrix in which the element A[x][y] lies.

Note: The matrix is divided into N equal submatrix each of size K*K (where K is the square root of N)

Examples:

Input: N = 9, x = 4, y = 4
mat = {{1, 2, 3, 9, 8, 7, 1, 2, 1}, {4, 5, 6, 1, 2, 3, 7, 9, 8}, {7, 8, 9, 2, 2, 0, 1, 5, 7},  
{0, 2, 9, 1, 2, 3, 4, 5, 3}, {9, 8, 7, 4, 5, 6, 7, 4, 1}, {1, 4, 7, 7, 8, 9, 9, 8, 7},  
{5, 6, 1, 9, 8, 7, 5, 2, 3}, {4, 5, 1, 6, 5, 4, 9, 7, 4}, {8, 7, 9, 3, 2, 1, 9, 4, 9}}, 
Output: {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Explanation: Given x = 4, y = 4 that element lies in the middle grid.

👁 Image
Input Matrix

Input: N = 9, x = 6, y= 4
mat = {{1, 2, 3, 9, 8, 7, 1, 2, 1}, {4, 5, 6, 1, 2, 3, 7, 9, 8}, {7, 8, 9, 2, 2, 0, 1, 5, 7},  
{0, 2, 9, 1, 2, 3, 4, 5, 3}, {9, 8, 7, 4, 5, 6, 7, 4, 1}, {1, 4, 7, 7, 8, 9, 9, 8, 7}, 
{5, 6, 1, 9, 8, 7, 5, 2, 3}, {4, 5, 1, 6, 5, 4, 9, 7, 4}, {8, 7, 9, 3, 2, 1, 9, 4, 9}}
Output: {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}
Explanation: Given x =6, y = 4 that element lies in the grid shown below.

👁 Image
Input Matrix

Approach: The problem can be solved based on the following observation:

An element at index (x, y) in a square matrix of perfect square length, lies in submatrix[n*(x/n), (n*(y/n)], where each value shows the positioning with respect to other submatrices. So the idea is to just print that submatrix. 

Follow the steps mentioned below to implement the idea:

  • Find square root on N.
  • Store the submatrix where the coordinate (x, y) lies in a new matrix.
  • Return the new array.

Below is the implementation of the above approach.


Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: