Check if possible to shuffle a matrix with adjacent movements
Last Updated :
14 Mar, 2023
Given a N x M matrix which represents the number of rows and number of columns respectively. Each cell of a matrix is occupied by exactly one student. The task is to determine whether we can shuffle each student in such a way that each student should occupy a cell that is adjacent to that student’s original cell, i.e. immediately to the left, right, top or bottom of that cell and after shuffling each cell should occupy by exactly one student.
Examples:
Input: N = 3, M = 3
Output: Shuffling not possible
Input: N = 4, M = 4
Output: Shuffling is possible
One possible way to shuffle the student is as shown below:
Approach: Check if the number of rows or the number of columns is even then shuffling is possible otherwise no shuffling is possible.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void Shuffling( int N, int M)
{
if (N % 2 == 0 || M % 2 == 0)
cout << "Shuffling is possible" ;
else
cout << "Shuffling not possible" ;
}
int main()
{
int N = 4, M = 5;
Shuffling(N, M);
return 0;
}
|
Java
import java.io.*;
class Main {
static void shuffling( int N, int M)
{
int a = N & 1 ;
int b = M & 1 ;
if (a != 1 || b != 1 )
System.out.println( "Shuffling is possible" );
else
System.out.println( "Shuffling not possible" );
}
public static void main(String[] args)
{
int N = 4 ,M = 5 ;
shuffling(N, M);
}
}
|
Python3
def Shuffling(N, M) :
if (N % 2 = = 0 or M % 2 = = 0 ) :
print ( "Shuffling is possible" );
else :
print ( "Shuffling not possible" );
if __name__ = = "__main__" :
N = 4 ;
M = 5 ;
Shuffling(N, M);
|
Javascript
<script>
function Shuffling(N, M)
{
if (N % 2 == 0 || M % 2 == 0)
document.write( "Shuffling is possible" );
else
document.write( "Shuffling not possible" );
}
var N = 4, M = 5;
Shuffling(N, M);
</script>
|
C#
using System;
class GFG
{
static void Shuffling( int N, int M)
{
if (N % 2 == 0 || M % 2 == 0)
Console.Write( "Shuffling is possible" );
else
Console.Write( "Shuffling not possible" );
}
public static void Main ()
{
int N = 4, M = 5;
Shuffling(N, M);
}
}
|
PHP
<?php
function Shuffling( $N , $M )
{
if ( $N % 2 == 0 || $M % 2 == 0)
echo "Shuffling is possible" ;
else
echo "Shuffling not possible" ;
}
$N = 4;
$M = 5;
Shuffling( $N , $M );
?>
|
Output
Shuffling is possible
Share your thoughts in the comments
Please Login to comment...