1+ /*
2+ Consider a rat placed at (0, 0) in a square matrix m[][] of order n and has to reach the destination at (n-1, n-1).
3+ Your task is to complete the function which returns a sorted array of strings denoting all the possible directions
4+ which the rat can take to reach the destination at (n-1, n-1). The directions in which the rat can move are 'U'(up),
5+ 'D'(down), 'L' (left), 'R' (right).
6+
7+ For example
8+ 1 0 0 0
9+ 1 1 0 1
10+ 1 1 0 0
11+ 0 1 1 1
12+
13+ For the above matrix the rat can reach the destination at (3, 3) from (0, 0) by two paths ie DRDDRR and DDRDRR
14+ when printed in sorted order we get DDRDRR DRDDRR.
15+ */
16+ using System ;
17+ using System . Collections . Generic ;
18+ using System . Linq ;
19+ using System . Text ;
20+ using System . Threading . Tasks ;
21+
22+ namespace GFG
23+ {
24+ class Program
25+ {
26+ static void Main ( String [ ] args )
27+ {
28+ int t = Int32 . Parse ( Console . ReadLine ( ) ) ;
29+ for ( int i = 0 ; i < t ; i ++ )
30+ {
31+ int n = Int32 . Parse ( Console . ReadLine ( ) ) ;
32+ int [ ] rc = Array . ConvertAll ( Console . ReadLine ( ) . Split ( ' ' ) , Int32 . Parse ) ;
33+ int [ , ] grid = new int [ n , n ] ;
34+ bool [ , ] visited = new bool [ n , n ] ;
35+ for ( int j = 0 ; j < n ; j ++ )
36+ {
37+ for ( int k = 0 ; k < n ; k ++ )
38+ {
39+ grid [ j , k ] = rc [ ( j * n ) + k ] ;
40+ }
41+ }
42+ if ( grid [ 0 , 0 ] == 1 ) RatPuzzle ( grid , visited , n , 0 , 0 , "" ) ;
43+ else Console . WriteLine ( "not possible" ) ;
44+ }
45+ }
46+ private static void RatPuzzle ( int [ , ] grid , bool [ , ] visited , int n , int row , int col , string s )
47+ {
48+ visited [ row , col ] = true ;
49+
50+ if ( row >= n || col >= n || row < 0 || col < 0 ) return ;
51+ if ( row == ( n - 1 ) && col == ( n - 1 ) )
52+ {
53+ Console . WriteLine ( s + " " ) ;
54+ }
55+
56+ if ( ( row + 1 ) < n && grid [ row + 1 , col ] == 1 && ! visited [ row + 1 , col ] )
57+ {
58+ RatPuzzle ( grid , visited , n , row + 1 , col , s + "D" ) ;
59+ }
60+ if ( ( col - 1 ) >= 0 && grid [ row , col - 1 ] == 1 && ! visited [ row , col - 1 ] )
61+ {
62+ RatPuzzle ( grid , visited , n , row , col - 1 , s + "L" ) ;
63+ }
64+ if ( ( col + 1 ) < n && grid [ row , col + 1 ] == 1 && ! visited [ row , col + 1 ] )
65+ {
66+ RatPuzzle ( grid , visited , n , row , col + 1 , s + "R" ) ;
67+ }
68+ if ( ( row - 1 ) >= 0 && grid [ row - 1 , col ] == 1 && ! visited [ row - 1 , col ] )
69+ {
70+ RatPuzzle ( grid , visited , n , row - 1 , col , s + "U" ) ;
71+ }
72+ visited [ row , col ] = false ;
73+ }
74+ }
75+ }
76+
0 commit comments