VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-it-is-possible-to-make-all-elements-into-1-except-obstacles/

⇱ Check if it is possible to make all elements into 1 except obstacles - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if it is possible to make all elements into 1 except obstacles

Last Updated : 30 Mar, 2023

Given a matrix M[][] of size N * M containing characters 0 and X. You have to choose a sub-matrix of 2*2 size, which doesn't contains X in it, and convert all the 0 under that sub-matrix into 1. Update M[][] after each operation. Return "YES", otherwise "NO" If it is possible to make all the zeros into ones except the cell containing X by using the given operation.

Examples:

Input: N = 3, M = 3

M[][]: 

0 0 X
0 0 0
0 0 0 
Output: YES
Explanation:

👁 Image
Graphical Explanation of input test case 1

It can be seen that from the initial matrix, at each operation a sub-matrix of size 2*2 is chose and convert all the zeros into ones under those sub-matrices using the given operation. It also noted that some sub-matrices contain 1 also, in this case remain the same. Any sub-matrix of size 2*2 doesn't contains 'X'. Therefore, it is possible to convert all the zeros into ones using given operation except X. Hence output is YES. 

Input: N = 4, M = 2

M[][]:

0 0 0 X
0 0 0 0
Output: NO
Explanation:

👁 Image
Graphical explanation of input test case 2

 It can be verified that all zeros in initial matrix can't be converted into ones.   

Approach: Implement the idea below to solve the problem:

The problem is observation based and can be solved by using those observations.

Steps were taken to solve the problem:

  1. Create a StringBuilder Array let's say X[] of size N.
  2. Initialize X[] with input matrix M[][].
  3. Run two nested loops for i = 0 to i < N - 1 and j = 0 to j < M - 1 and follow the below-mentioned steps under the scope of the loop:
    • If ( X[ i ].charAt( j ) == '0' || X[ i ].charAt( j ) == '1' )
      • If ( X[ i ].charAt(j + 1) != 88 && X[i + 1].charAt(j + 1) != 88 && X[i + 1].charAt( j ) != 88)
        • X[ i ].setCharAt(j, '1')
        • X[ i ].setCharAt(j + 1, '1')
        • X[i + 1].setCharAt(j, '1')
        • X[i + 1].setCharAt(j + 1, '1')
  4. Now, just traverse the X[] and check if there exists 0 or not. If 0 exists then output NO or else YES

Below is the code to implement the approach:


Output
NO

Time Complexity: O(N*M)
Auxiliary Space: O(N*M), As StringBuilder is used of size N*M.

Comment
Article Tags: