fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. int grid[6][6];
  5.  
  6. int recursive_path(int r1,int c1,int r2,int c2,int row,int col) {
  7. // cout<<r1<<' '<<c1<<" t\n";
  8. if(r1<0 || c1<0 || r1>=row || c1>=col) {
  9. return -10000;
  10. }
  11. if(grid[r1][c1]==1) {
  12. return -10000;
  13. }
  14. if(r1==r2 && c1==c2) {
  15. return 0;
  16. }
  17. grid[r1][c1]=1;
  18. int currmax=-10000;
  19. currmax=max(currmax,recursive_path(r1+1,c1,r2,c2,row,col));
  20. currmax=max(currmax,recursive_path(r1-1,c1,r2,c2,row,col));
  21. currmax=max(currmax,recursive_path(r1,c1+1,r2,c2,row,col));
  22. currmax=max(currmax,recursive_path(r1,c1-1,r2,c2,row,col));
  23. grid[r1][c1]=0;
  24. return 1+currmax;
  25. }
  26.  
  27. int main()
  28. {
  29. int t;
  30. cin>>t;
  31. while(t--) {
  32. int row,col;
  33. cin>>row>>col;
  34. int r1,c1,r2,c2;
  35. cin>>r1>>c1>>r2>>c2;
  36. string mat[row];
  37. for(int i=0;i<row;i++) {
  38. cin>>mat[i];
  39. for(int j=0;j<col;j++) {
  40. if(mat[i][j]=='#') {
  41.  
  42. grid[i][j]=1;
  43. } else {
  44. grid[i][j]=0;
  45. }
  46. }
  47. }
  48. int val=recursive_path(r1,c1,r2,c2,row,col);
  49. if(val<0) {
  50. cout<<"-1\n";
  51. } else {
  52. cout<<val<<'\n';
  53. }
  54. // t=0;
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 15240KB
stdin
4
1 5
0 1 0 0
.....
2 3
0 0 1 2
...
.#.
5 2
4 0 0 0
..
#.
.#
..
..
5 5
1 2 4 0
.....
.....
.....
.....
.....
stdout
1
3
-1
23