新学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));
}
}