text: Java program to implement the above approach
code: 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 [ ] [ ] mat = new int [ 1001 ] [ 1001 ] ; static int r , c , x , y ;