Java implementation for the above approach
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int n = 6 ; static int m = 6 ; static int dx [ ] = { 0 , 1 , - 1 , 0 } ; static int dy [ ] = { 1 , 0 , 0 , - 1 } ;