Search ingredient in Matrix – GeeksforGeeks

0
7


View Dialogue

Enhance Article

Save Article

Like Article

Given an N×N matrix mat[][] and an integer Ok, the duty is to go looking Ok in mat[][] and if discovered return its indices.

Examples:

Enter: mat[][] = {{1, 2, 3}, {7, 6, 8}, {9, 2, 5}}, Ok = 6
Output: {1, 1}
Clarification: mat[1][1] = 6

Enter: mat[][] = {{3, 4, 5, 0}, {2, 9, 8, 7}}, Ok = 10
Output: Not Discovered

 

Method:

Traverse the matrix utilizing nested loops and if the goal is discovered then, return its indices

Comply with the steps to resolve this downside:

  • Take the matrix (2-D array) and goal as enter.
  • Apply two nested for-loop with i and j variables respectively.
    • If mat[i][j] = Ok return the indices pair {i, j}
  • If the goal just isn’t discovered print “Not Discovered”.

Beneath is the implementation of this strategy

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

pair<int, int> FindPosition(vector<vector<int> > M,

                            int Ok)

{

    for (int i = 0; i < M.measurement(); i++) {

        for (int j = 0; j < M[i].measurement(); j++) {

            if (M[i][j] == Ok)

                return { i, j };

        }

    }

    return { -1, -1 };

}

  

int primary()

{

    

    vector<vector<int> > M{ { 1, 2, 3 },

                            { 7, 6, 8 },

                            { 9, 2, 5 } };

    int Ok = 6;

  

    

    pair<int, int> p = FindPosition(M, Ok);

    if (p.first == -1)

        cout << "Not Discovered" << endl;

    else

        cout << p.first << " " << p.second;

    return 0;

}

Time Complexity: O(N2)
Auxiliary House: O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here