fork download
  1. #include <bits/stdc++.h>
  2. #define N 1000000000
  3. #define ll long long
  4. using namespace std;
  5.  
  6. int a[11][11]={},n,ok=0;
  7. int s[1000];
  8.  
  9. void Try(int i,int j,int pos){
  10. if(i==n-1 && j==n-1){
  11. for(int i=0;i<pos;++i){
  12. if(s[i]==0) cout <<'D';
  13. if(s[i]==1) cout <<'L';
  14. if(s[i]==2) cout <<'R';
  15. if(s[i]==3) cout <<'U';
  16. }
  17. cout <<" ";
  18. ok=1;
  19. return;
  20. }
  21. if(i<n-1 && a[i+1][j]==1){ // check down
  22. a[i+1][j]=0;
  23. s[pos]=0;
  24. Try(i+1,j,pos+1);
  25. a[i+1][j]=1;
  26. }
  27. if(j<n-1 && j>0 && a[i][j-1]==1){ // check left
  28. a[i][j-1]=0;
  29. s[pos]=1;
  30. Try(i,j-1,pos+1);
  31. a[i][j-1]=1;
  32. }
  33. if(j<n-1 && a[i][j+1]==1){ // check right
  34. a[i][j+1]=0;
  35. s[pos]=2;
  36. Try(i,j+1,pos+1);
  37. a[i][j+1]=1;
  38. }
  39. if(i<n-1 && i>0 && a[i-1][j]==1){ //check up
  40. a[i-1][j]=0;
  41. s[pos]=3;
  42. Try(i-1,j,pos+1);
  43. a[i-1][j]=1;
  44. }
  45. }
  46.  
  47. int main(){
  48. //freopen("input.txt","r",stdin);
  49. int t; cin>>t;
  50. while(t--){
  51. cin>>n;
  52. for(int i=0;i<n;i++)
  53. for(int j=0;j<n;++j) cin>>a[i][j];
  54. for(int i=0;i<n;i++){
  55. for(int j=0;j<n;++j){
  56. cout << a[i][j]<<" ";
  57. }
  58. cout << endl;
  59. }
  60. if(a[0][0]==0||a[n-1][n-1]==0) cout<<-1;
  61. else{
  62. Try(0,0,0);
  63. if(ok==0) cout<<-1;
  64. }
  65. ok=0;
  66. cout<<endl;
  67. //s="";
  68. }
  69. }
Success #stdin #stdout 0s 4512KB
stdin
3
4
1 0 0 0
1 1 0 1
0 1 0 0
0 1 1 1
4
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1
5
1 0 0 0 0
1 1 1 1 1
1 1 1 0 1
0 0 0 0 1
0 0 0 0 1
stdout
1 0 0 0 
1 1 0 1 
0 1 0 0 
0 1 1 1 
DRDDRR 
1 0 0 0 
1 1 0 1 
1 1 0 0 
0 1 1 1 
DDRDRR DRDDRR 
1 0 0 0 0 
1 1 1 1 1 
1 1 1 0 1 
0 0 0 0 1 
0 0 0 0 1 
DDRRURRDDD DDRURRRDDD DRDRURRDDD DRRRRDDD