Google考题试解 - BusStops

新学java,试解google考题 ,欢迎批评。

http://blog.csdn.net/cyp403/archive/2005/12/13/550943.aspx

public class BusStops {
  public int countStops(String[] cityMap, int walkingDistance) {
   
    final char stopChar = 'B', iChar = 'X';
   
    //my position
    int myX=0, myY=0;
   
    int x,y;
    int distance;
    int count=0;

    // search "I"
    for (y = 0; y < cityMap.length ; y++) {
        x = cityMap[y].indexOf(iChar);
        if (x >= 0) {
          myX = x;
          myY = y;
          break;
        }
    }

    //calculate distance between every busStop and I
    for(y = 0; y < cityMap.length; y++) {
      x = -1;
      do {
        x = cityMap[y].indexOf(stopChar, x+1);
        if (x >= 0) {
          distance=Math.abs(x-myX)+Math.abs(y-myY);
          if(distance<=walkingDistance){
            count++;
          }
        } else {
          break;
        }
      } while (x >= 0);
    }
    return count;
  }
 
  public static void main(String args[]){
    String[] city1=
    {"...B.",
      ".....",
      "..X.B",
      ".....",
      "B...."};
    int limit1=3;
   
    String[] city2=
     {"B.B..",
      ".....",
      "B....",
      ".....",
      "....X"};
    int limit2=8;
   
    String[] city3=
    { "BBBBB",
      "BB.BB",
      "B.X.B",
      "BB.BB",
      "BBBBB"};
     int limit3=1;
    
     String[] city4=
     {"B..B..",
      ".B...B",
      "..B...",
      "..B.X.",
      "B.B.B.",
      ".B.B.B"};
     int limit4=3;
   
     BusStops bs=new BusStops();
  
     System.out.println(bs.countStops(city1, limit1));
     System.out.println(bs.countStops(city2, limit2));
     System.out.println(bs.countStops(city3, limit3));
     System.out.println(bs.countStops(city4, limit4));
   
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值