fork(1) download
  1. import java.util.Scanner;
  2.  
  3. public class Main{
  4. static int depth=0;
  5. static int parr[][]=null,stack[][]=null;
  6. static int n,m,enr,enc,maxstep=0,step=0;
  7.  
  8. public static void main(String args[])
  9. {
  10. int str,stc;
  11. Scanner scan=new Scanner(System.in);
  12. n=scan.nextInt();
  13. m=scan.nextInt();
  14.  
  15. str=scan.nextInt()-1;
  16. stc=scan.nextInt()-1;
  17. enr=scan.nextInt()-1;
  18. enc=scan.nextInt()-1;
  19. parr=new int [n][m];
  20. parr[str][stc]=1;
  21.  
  22. stack=new int [n*m+1][8];
  23. //
  24. // find(str,stc,1);
  25. stack[0][0]=str;stack[0][1]=stc;stack[0][2]=step;stack[0][3]=0;
  26. //stack[0][0]=str;stack[0][1]=stc;stack[0][2]=step;
  27. int i,nstr,nstc;
  28. while(stack[0][3]<=4)
  29. {
  30. //System.out.println(step);
  31. i=++stack[step][3];
  32. //str=stack[step]
  33. if(i>4){parr[stack[step][0]][stack[step][1]]=0; /* stack[step][3]=0;*/ step--;continue;}
  34.  
  35. str=stack[step][0];
  36. stc=stack[step][1];
  37.  
  38. nstr=str;
  39. nstc=stc;
  40.  
  41. if(i==1)
  42. {
  43. if(str>0 && parr[str-1][stc]!=1)
  44. nstr-=1;
  45. }
  46.  
  47. if(i==2)
  48. {
  49. if(stc>0 && parr[str][stc-1]!=1)
  50. nstc-=1;
  51. }
  52.  
  53. if(i==3)
  54. {
  55. if(str<n-1 && parr[str+1][stc]!=1)
  56. nstr+=1;
  57. }
  58.  
  59. if(i==4)
  60. {
  61. if(stc<n-1 && parr[str][stc+1]!=1)
  62. nstc+=1;
  63. }
  64.  
  65. if(str==nstr && stc==nstc)
  66. {
  67.  
  68.  
  69.  
  70. continue;
  71. }
  72.  
  73.  
  74. else
  75. {
  76. //parr[nstr][nstc]=1;
  77. //step++;
  78. //chk target reached
  79. if(nstr==enr && nstc==enc)
  80. {
  81. if(maxstep==0)maxstep=step+1;else if(step+1>maxstep){maxstep=step+1;/*System.out.println(step+1);*/}
  82.  
  83. //step--;
  84. //parr[nstr][nstc]=0;
  85. continue;
  86.  
  87. }
  88. else
  89. {
  90. parr[nstr][nstc]=1;
  91. step++;
  92. //find(nstr,nstc,step);
  93.  
  94. stack[step][0]=nstr;stack[step][1]=nstc;stack[step][3]=0;
  95.  
  96.  
  97. //step--;
  98. // depth--;
  99. // System.out.println(depth);
  100. //parr[nstr][nstc]=0;
  101.  
  102. }
  103.  
  104.  
  105.  
  106.  
  107.  
  108. }
  109.  
  110.  
  111.  
  112.  
  113. }
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120. System.out.println("Maximum step="+(maxstep+1));
  121.  
  122. }
  123.  
  124. }
Success #stdin #stdout 1.87s 216128KB
stdin
6 6
1 1
6 6
stdout
Maximum step=35