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:
Create a StringBuilder Array let's say X[] of size N.
Initialize X[] with input matrix M[][].
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' )