Examine if adjoining cell of Begin might be reached visiting all cells as soon as

[ad_1]

Given two integers X and Y, which signify the variety of rows and columns respectively of a matrix, the duty is to test whether or not there exists a path, Which follows all of the under circumstances:

  • Beginning of the trail is from the cell (1, 1).
  • Ending of the trail is any cell adjoining to (1, 1).
  • You need to traverse every cell of the matrix solely as soon as.

Notice: Right here 1 based mostly indexing is used.

Examples:

Enter:  X = 2, Y = 3
Output: YES
Rationalization:

Explanation for input test case

Rationalization for enter check case

Every cell is traversed as soon as, beginning cell is (1, 1) and ending cell is (2, 1), Which is adjoining to (1, 1). Therefore, all of the circumstances met.

Enter: X = 1, Y = 1
Output: NO
Rationalization:  As there isn’t any adjoining cell of ( 1, 1 ) exists due to this fact, Output is NO.

Strategy: The issue might be solved based mostly on the next statement:

Remark:

Let’s take some random test-cases. 

Take a look at case 1: X = 4, Y = 4 
Output: YES
Rationalization:

Explanation for test case 1

Rationalization for check case 1

Take a look at case 2:  X=4, Y=5
Output: YES
Rationalization:

Explanation for test case 2

Rationalization for check case 2

Take a look at case 3: X = 1, Y =3 
Output: NO
Rationalization: No path is feasible that fulfill given constraints.

From all above check circumstances, We will conclude some circumstances:

  • If each X and Y are odd, Then there exists no path.
  • If (X = 1 && Y > 2) or (Y = 1 && X > 2), Then no path exists.
  • All of the circumstances besides above mentioned 2( quantity 1 and quantity 2 ) circumstances can have a path.    

Comply with the under steps to implement the thought:

  • Examine the circumstances on X and Y mentioned above.
  • If the values match any of the primary two circumstances then no path is feasible.
  • In any other case, there exists a path.

Under is the implementation of the above strategy.

Java

  

import java.io.*;

import java.lang.*;

import java.util.*;

  

class GFG {

  

    

    public static void most important(String args[])

    {

        lengthy X = 2, Y = 2;

  

        

        System.out.println(Is_Path_Possible(X, Y));

    }

  

    

    static String Is_Path_Possible(lengthy X, lengthy Y)

    {

        

        

        if (X % 2 != 0 && Y % 2 != 0 || X == 1 && Y > 2

            || Y == 1 && X > 2) {

  

            return "NO";

        }

        else {

            return "YES";

        }

    }

}

Time Complexity: O(1)
Auxiliary House: O(1)  

[ad_2]

Leave a Reply