Search in a row-wise and column-wise sorted matrix in C++The problem specifies that we are given an integer, X, and a sorted row-wise and column-wise matrix. We must determine whether the number provided, "X", has been found in this matrix; if it is, display the exact position of the X; if not, print it out as "Not Found". Example:Input: { {12, 2, 13, 9}, {58 6, 7, 8}, {9, 11, 61, 62}, {19, 43, 15, 45} } X = 8 is the element to be discovered. You can iterate throughout the matrix, beginning with the top left corner (1st row, 1st column) and comparing each member to the desired value (in this case, 8). Comparison in the first row:Element at the index 1,1: 1 (Not equal to 8) Element at the index 1,2: 2 (Not equal to 8) Element at the index 1,3: 3 (Not equal to 8) Element at the index1,4: 4 (Not equal to 8) In the second row, there is a comparison:Position 2: 1 Element: 5 (Not equivalent to 8) Element at the index 2,2: 6 (Not equal to 8) Element at the index 2,3: 7 (Not equal to 8) Element at the index 2,4: 8 (Equal to 8) Output: As a result, element 8 appears in the second row, fourth column, and position 2,4. Naive ApproachIn the Naive technique, we can scan the entire row-wise and column-wise sorted matrix and search for the provided element. If it is found, print its location. Algorithm StepsL=:
Filename: Row_col_index.cpp Output: The element found At 2,4 Analysis of ComplexityTime complexity: O(R*C) Explanation: R is the number of rows in this row-wise and column-wise sorted matrix, and C is the number of columns in this row-wise and column-wise ordered matrix. The time complexity becomes O(R*C) for this program because we access the entire array. Space Complexity: O(1) Explanation: There is no need for additional space. Greedy Approach (Optimized)The objective is to delete rows or columns in each comparison until we reach the necessary number or are beyond the range. We'll begin at the top right corner of the matrix. There are three possible ways for this approach.
Algorithm Steps:
Filename: Row_col_index2.cpp Output: The element has been found At 2,4 Analysis of ComplexityTime complexity: O(N+M) Explanation: R is the total number of rows in this row-wise and column-wise sorted matrix, and C is the total number of columns in this row-wise and column-wise ordered matrix. The worst-case Time complexity is O(N+M) because we only read one row and column. Space Complexity: O(1) Explanation: There is no need for additional space. Next TopicSet insertion and deletion in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India