crazy king

package crazy_king; import java.util.Scanner; public class Solution { static int row,col,A_row,A_col,B_row,B_col; static String s; static char[] a[]; static int visit[][]; static int rque[]=new int[1000000]; static int cque[]=new int[1000000]; static int left,right; static Scanner sc; static int dr[]={0,0,1,-1,1,-1,1,-1}; static int dc[]={1,-1,0,0,-1,1,1,-1}; static int dr1[]={2,2,-2,-2,1,1,-1,-1}; static int dc1[]={1,-1,-1,1,2,-2,2,-2}; static void push(int r,int c) { rque[right]=r; cque[right++]=c; } static void danhdau() { int nr,nc; for(int i=0;i<row;i++) for(int j=0;j<col;j++) { if(a[i][j]=='Z') { visit[i][j]=-1; for(int k=0;k<8;k++) { nr=i+dr1[k]; nc=j+dc1[k]; if(nc>=0 && nr>=0 && nc<col && nr<row ) { visit[nr][nc]=-1; } } } } visit[B_row][B_col]=0; } static void bfs(int rstart,int cstart) { left=0; right=0; push(rstart,cstart); int r,c, nr,nc; visit[rstart][cstart]=1; while(left!=right) { r=rque[left]; c=cque[left++]; for(int i=0;i<8;i++) { nr=r+dr[i]; nc=c+dc[i]; if(nr>=0 && nc>=0 && nr<row && nc<col) { if(visit[nr][nc]==0) { visit[nr][nc]=visit[r][c]+1; push(nr,nc); } } } } } public static void main(String[] args) { sc = new Scanner(System.in); int T=sc.nextInt(); for(int t=1;t<=T;t++) { col=sc.nextInt(); row=sc.nextInt(); a=new char[row][col]; visit=new int[row][col]; for(int i=0;i<row;i++) { s=sc.next(); a[i]=s.toCharArray(); } for(int i=0;i<row;i++) for(int j=0;j<col;j++) { if(a[i][j]=='A'){ A_row=i; A_col=j; } else if(a[i][j]=='B') { B_row=i; B_col=j; } } //================================ danhdau(); bfs(A_row,A_col); if(visit[B_row][B_col]==0) System.out.println(-1); else System.out.println(visit[B_row][B_col]-1); } } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.