Friday, August 5, 2022
HomeWordPress DevelopmentSearch factor in Matrix - GeeksforGeeks

Search factor in Matrix – GeeksforGeeks


View Dialogue

Enhance Article

Save Article

Like Article

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

Examples:

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

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

 

Strategy:

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

Comply with the steps to unravel 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] = Okay return the indices pair {i, j}
  • If the goal will not be discovered print “Not Discovered”.

Under is the implementation of this strategy

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

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

                            int Okay)

{

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

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

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

                return { i, j };

        }

    }

    return { -1, -1 };

}

  

int major()

{

    

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

                            { 7, 6, 8 },

                            { 9, 2, 5 } };

    int Okay = 6;

  

    

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

    if (p.first == -1)

        cout << "Not Discovered" << endl;

    else

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

    return 0;

}

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments