Problem Statement
You are given a String[] cityMap representing the layout of a city. The city consists of blocks. The first element of cityMap represents the first row of blocks, etc. A 'B' character indicates a location where there is a bus stop. There will be exactly one 'X' character, indicating your location. All other characters will be '.'. You are also given an int walkingDistance, which is the maximum distance you are willing to walk to a bus stop. The distance should be calculated as the number of blocks vertically plus the number of blocks horizontally. Return the number of bus stops that are within walking distance of your current location.
Definition
Class:BusStops
Method:countStops
Parameters:String[], int
Returns:int
Method signature:int countStops(String[] cityMap, int walkingDistance)
(be sure your method is public)
Constraints
-cityMap will contain between 1 and 50 elements, inclusive.
-Each element of cityMap will contain between 1 and 50 characters, inclusive.
-Each element of cityMap will contain the same number of characters.
-Each character of each element of cityMap will be 'B', 'X', or '.'.
-There will be exactly one 'X' character in cityMap.
-walkingDistance will be between 1 and 100, inclusive.
Examples
0)
{"...B.",
".....",
"..X.B",
".....",
"B...."}
3
Returns: 2
You can reach the bus stop at the top (3 units away), or on the right (2 units away). The one in the lower left is 4 units away, which is too far.
1)
{"B.B..",
".....",
"B....",
".....",
"....X"}
8
Returns: 3
A distance of 8 can get us anywhere on the map, so we can reach all 3 bus stops.
2)
{"BBBBB",
"BB.BB",
"B.X.B",
"BB.BB",
"BBBBB"}
1
Returns: 0
Plenty of bus stops, but unfortunately we cannot reach any of them.
3)
{"B..B..",
".B...B",
"..B...",
"..B.X.",
"B.B.B.",
".B.B.B"}
3
Returns: 7
說(shuō)實(shí)話我覺(jué)得這一題沒(méi)啥意思,超簡(jiǎn)單,首先先確定X的位置,再用遍歷數(shù)組找B的位置,再求相減的絕對(duì)值然后判斷是否超出給出的最大距離就行了。相對(duì)這題PlayCars卻很有意思,到現(xiàn)在我也沒(méi)想出除了窮舉以外的一個(gè)更好的算法,因?yàn)槲矣X(jué)得窮舉可能會(huì)超時(shí)。有哪位有其它的辦法的話,請(qǐng)告訴我,大家探討一下,謝謝。好了,不廢話了,下面是這題的答案:
public class BusStops {
public static void main(String[] arg){
BusStops total = new BusStops();
System.out.println(total.countStops({"...B.",".....","..X.B",".....","B...."},3));
}
public int countStops(String[] cityMap, int walkingDistance){
int sum= 0;
int locationX = -1;
int locationY = -1;
for(int i=0;i<cityMap.length;i++){
for(int j=0;j<cityMap[i].length();j++){
if(cityMap[i].charAt(j)=='X'){
locationX = i;
locationY = j;
}
}
}
for(int i=0;i<cityMap.length;i++){
for(int j=0;j<cityMap[i].length();j++){
if(cityMap[i].charAt(j)=='B' && (Math.abs(locationX - i) + Math.abs(locationY - j)<=walkingDistance))
sum++;
}
}
return sum;
}
}