Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- public class SortestPath {
- int[] fx={1,-1,0,0};
- int[] fy={0,0,1,-1};
- int bfs(char[][] cell,int sx,int sy,int ex,int ey,int row,int col)
- {
- // for(int i=0;i<row;i++)
- // {
- // for(int j=0;j<col;j++)
- // System.out.print(cell[i][j]);
- // System.out.println();
- // }
- //
- int[][] d=new int[row+3][col+3];
- //int[][] vis=new int[row+3][col+3];
- //System.out.println(sx+","+sy);
- cell[sx][sy]='1';
- Queue<int[]> q=new LinkedList<int[]>();
- int[] XY=new int[2];
- XY[0]=sx;
- XY[1]=sy;
- q.add(XY);
- d[sx][sy]=1;
- while(q.peek()!=null)
- {
- int[] top=new int[2];
- top=q.poll();
- for(int k=0;k<4;k++)
- {
- int tx=top[0]+fx[k];
- int ty=top[1]+fy[k];
- if(tx>=0 && tx<row && ty>=0 && ty<col && cell[tx][ty]!='1')
- {
- cell[tx][ty]='1';
- d[tx][ty]=d[top[0]][top[1]]+1;
- top[0]=tx;
- top[1]=ty;
- if(top[0]==ex&&top[1]==ey)
- return d[tx][ty];
- q.add(top);
- }
- }
- }
- return -1;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int t;
- int casno=1;
- Scanner sc=new Scanner(System.in);
- t=sc.nextInt();
- while(t--!=0)
- {
- int i;
- //int[] rc=new int[2];
- // for(i=0;i<2;i++)
- // rc[i]=sc.nextInt();
- // int row=rc[0],col=rc[1];
- int row=sc.nextInt(); int col=sc.nextInt();
- // System.out.println(row+"row"+col);
- char[][] cell=new char[row][col];
- for(i=0;i<row;i++)
- {
- String str =sc.next();
- // System.out.println(str);
- cell[i] = str.toCharArray();
- }
- int[] sxy=new int[2];
- int[] exy=new int[2];
- for(i=0;i<2;i++)
- sxy[i]=sc.nextInt();
- for(i=0;i<2;i++)
- exy[i]=sc.nextInt();
- SortestPath ob=new SortestPath();
- int n=ob.bfs(cell, sxy[0], sxy[1], exy[0], exy[1], row, col);
- System.out.println("Case "+casno++ +": "+n);
- }
- sc.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement