VOOZH about

URL: https://www.geeksforgeeks.org/dsa/searching-algorithms-for-a-2d-arrays-matrix/

⇱ Search in an Unsorted Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Search in an Unsorted Matrix

Last Updated : 8 May, 2026

Given a 2D integer array mat[][] and a number x, find whether element x is present in the matrix or not.

Examples:

Input: mat[][] = [[6, 23, 21], [4, 45, 32], [69, 11, 87]], x = 32
Output: true
Explanation: 32 is present in the matrix.

Input: mat[][] = [[14, 34, 23, 95, 43, 28]], x = 55
Output: false
Explanation: 55 is not present in the matrix.

We traverse all elements row by row and compare each element with the target x. If a match is found, we return true; otherwise, after completing the traversal, we return false.

Let us understand with an example:

Input: mat = [[6, 23, 21], [4, 45, 32], [69, 11, 87]], x = 32

Start from first row:

  • At (0, 0) -> value = 6, not equal to x -> move right
  • At (0, 1) -> value = 23, not equal to x -> move right
  • At (0, 2) -> value = 21, not equal to x -> move to next row

Move to second row:

  • At (1, 0) -> value = 4, not equal to x -> move right
  • At (1, 1) -> value = 45, not equal to x -> move right
  • At (1, 2) -> value = 32, equal to x -> element found, return true

Traversal stops as soon as an element is found. Final Output: true


Output
true

There are more versions of searching in a matrix, please refer the below articles.

Comment