Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.Scanner;
  4.  
  5. public class SortestPath {
  6.  
  7.  
  8. int[] fx={1,-1,0,0};
  9. int[] fy={0,0,1,-1};
  10.  
  11. int bfs(char[][] cell,int sx,int sy,int ex,int ey,int row,int col)
  12. {
  13. // for(int i=0;i<row;i++)
  14. // {
  15. // for(int j=0;j<col;j++)
  16. // System.out.print(cell[i][j]);
  17. // System.out.println();
  18. // }
  19. //
  20. int[][] d=new int[row+3][col+3];
  21. //int[][] vis=new int[row+3][col+3];
  22. //System.out.println(sx+","+sy);
  23. cell[sx][sy]='1';
  24. Queue<int[]> q=new LinkedList<int[]>();
  25. int[] XY=new int[2];
  26. XY[0]=sx;
  27. XY[1]=sy;
  28. q.add(XY);
  29. d[sx][sy]=1;
  30. while(q.peek()!=null)
  31. {
  32. int[] top=new int[2];
  33. top=q.poll();
  34. for(int k=0;k<4;k++)
  35. {
  36. int tx=top[0]+fx[k];
  37. int ty=top[1]+fy[k];
  38. if(tx>=0 && tx<row && ty>=0 && ty<col && cell[tx][ty]!='1')
  39. {
  40. cell[tx][ty]='1';
  41. d[tx][ty]=d[top[0]][top[1]]+1;
  42. top[0]=tx;
  43. top[1]=ty;
  44. if(top[0]==ex&&top[1]==ey)
  45. return d[tx][ty];
  46. q.add(top);
  47. }
  48. }
  49. }
  50. return -1;
  51. }
  52.  
  53. public static void main(String[] args) {
  54. // TODO Auto-generated method stub
  55. int t;
  56. int casno=1;
  57. Scanner sc=new Scanner(System.in);
  58. t=sc.nextInt();
  59. while(t--!=0)
  60. {
  61. int i;
  62. //int[] rc=new int[2];
  63. // for(i=0;i<2;i++)
  64. // rc[i]=sc.nextInt();
  65. // int row=rc[0],col=rc[1];
  66. int row=sc.nextInt(); int col=sc.nextInt();
  67. // System.out.println(row+"row"+col);
  68. char[][] cell=new char[row][col];
  69.  
  70. for(i=0;i<row;i++)
  71. {
  72. String str =sc.next();
  73. // System.out.println(str);
  74. cell[i] = str.toCharArray();
  75. }
  76.  
  77.  
  78.  
  79.  
  80. int[] sxy=new int[2];
  81. int[] exy=new int[2];
  82. for(i=0;i<2;i++)
  83. sxy[i]=sc.nextInt();
  84. for(i=0;i<2;i++)
  85. exy[i]=sc.nextInt();
  86. SortestPath ob=new SortestPath();
  87. int n=ob.bfs(cell, sxy[0], sxy[1], exy[0], exy[1], row, col);
  88.  
  89. System.out.println("Case "+casno++ +": "+n);
  90.  
  91. }
  92. sc.close();
  93.  
  94. }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement