...

/

Solution: Search in a 2D Array

Solution: Search in a 2D Array

Explore various approaches to solving the challenge of determining whether a number is present in a 2D array.

Solution 1: Brute force

using System;
class Program
{
/// <summary>
/// A method to find a number in a 2D array.
/// </summary>
/// <param name="arr">A 2D array of integers.</param>
/// <param name="number">A number to be searched in the 2D array.</param>
/// <returns>True if the number is found, otherwise False.</returns>
public static bool FindIn(int[][] arr, int number)
{
int numRows = arr.Length;
int numCols = arr[0].Length;
for (int i = 0; i < numRows; i++) // Number of rows
{
for (int j = 0; j < numCols; j++) // Number of cols
{
if (arr[i][j] == number)
{
return true; // If number is found
}
}
}
return false; // If number is not found
}
// Driver to test above code
static void Main()
{
int[][] array = new int[][]
{
new int[] { 10, 11, 12, 13 },
new int[] { 14, 15, 16, 17 },
new int[] { 27, 29, 30, 31 },
new int[] { 32, 33, 39, 50 }
};
// Example 1
Console.WriteLine(FindIn(array, 30));
// Example 2
Console.WriteLine(FindIn(array, 100));
}
}

Explanation

Here, we perform a simple linear search in the entire 2D array using two for loops.

Time complexity

Since we use two nested for loops, the time complexity is O(nm ...