zoj 1091 Queue


zoj 1091


//package adt ;
import  java.lang.*; 

//import  adt.Animal ; 
import  java.util.*; 

class  Node{
	    public int x , y , step ;
	    Node(){}
	    Node(int x , int y , int step){
	  	  this.x = x ;
	  	  this.y = y ;
	  	  this.step = step ;
	    }
}

public class Main{

	 
	   public static Node S = new Node() , T = new Node() ;
	   public static boolean vis[][] = new boolean[10][10] ;
	   
	   public static int [][] d= {{1 , -2} , {1 , 2} , {-1 , -2} , {-1 , 2} ,
	                        {2 , 1} , {2 , -1} , {-2 , -1} , {-2 , 1} } ; 
	   
	   public static boolean cango(int x , int y){
		      return 1 <= x && x <= 8 && 1 <= y && y <= 8 ;
	   } 
	   
	   public static int bfs(){
		      Queue<Node> q = new LinkedList<Node>() ;      
		      Node now = new Node() ;
		      
		      for(int i = 1 ; i <= 8 ; i++){
		    	  for(int j = 1 ; j <= 8 ; j++) vis[i][j] = false ;
		      }
		      
		      vis[S.x][S.y] = false  ;
		      
		      q.add(S) ;
		      while(! q.isEmpty()){
		    	    now = q.poll() ;
		    	    if(now.x == T.x && now.y == T.y)  return now.step ;
		    	    for(int i = 0 ; i < d.length ; i++){
		    	    	  int x = now.x + d[i][0] ;
		    	    	  int y = now.y + d[i][1] ;
		    	          if(cango(x , y) && ! vis[x][y]){
		    	        	    vis[x][y] = true ;
		    	        	    q.add(new Node(x , y , now.step + 1)) ;
		    	          }	  
		    	    }
		      }
		      
		      return -1 ;
	   } 
	
	   public static void main(String srgs[]){      
	          
		      Scanner cin = new Scanner(System.in) ;
	          String  sa , sb ;
	        
	          while(cin.hasNext()){
	        	    sa = cin.next() ;
	        	    S.x = sa.charAt(0) - 'a' + 1 ;
	        	    S.y = sa.charAt(1) - '0' ;
	        
	        	    sb =  cin.next() ;
	        	    T.x = sb.charAt(0) - 'a' + 1 ;
	        	    T.y = sb.charAt(1) - '0' ;
	               
	        	    S.step = 0 ;
	        	    
	        	    System.out.printf("To get from %s to %s takes %d knight moves.\n", sa , sb , bfs() ) ;

	          }
	           
	   }
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值