話說你在走路上班時,經過一片種植蘿蔔的農田。這塊田地的形狀是一個矩形的網格。field的第i個元素的第j個字元,表示田地的第i
行第j列的格子裡包含的蘿蔔的數目。我們定義一個格子的特殊程度為它周圍所有格子的蘿蔔個數的和;
它周圍的格子包含它上下左右以及對角相鄰的格子,最多有8個,在田地的邊界上的格子會少一些。如果一個格子周圍沒有別的格子,則它的特殊程度為0。
請返回田地中特殊程度在A和B之間的所有格子的數目(包含A,B)。
Definition
Class: NumberField
Method: countSpecialNumbers
Parameters: string[], int, int
Returns: int
Method signature: int countSpecialNumbers(string[] field, int A, int B)
(be sure your method is public)
Constraints
- field 包含1個到50個元素,含1和50。
- field的每個元素包含1個到50個字元,含1和50。
- field的每個元素包含相同的字元數。
- field的每個元素的字元均為’0’到’9’之一。
- A的範圍會在0到100之間,含0和100。
- B 的範圍會在A到100之間,含A和100。
Examples
0)
{"111",
"111",
"111"}
4
8
Returns: 5
在這塊田地裡面,位於角落的格子的特殊程度是3,位於中間的格子的特殊程度是8,其他4個格子的特殊程度為5。
1)
{"111",
"141",
"111"}
4
8
Returns: 9
現在所有的9個格子都滿足要求。
2)
{"2309",
"0239",
"2314"}
5
7
Returns: 3
3)
{"924",
"231",
"390",
"910",
"121"}
31
36
Returns: 0
4)
{"5"}
3
8
Returns: 0
5)
{"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890"}
3
18
Returns: 26
public class NumberField {
public static void main(String[] args) {
NumberField n = new NumberField();
String field[] = { "1234567890", "1234567890", "1234567890",
"1234567890", "1234567890", "1234567890", "1234567890",
"1234567890", "1234567890", "1234567890", "1234567890" };
System.out.println(n.countSpecialNumbers(field, 3, 18));
}
public int countSpecialNumbers(String[] field, int A, int B) {
int count = 0;
for (int r = 0; r < field.length; r++) {
for (int c = 0; c < field[r].length(); c++) {
int temp = getCount(field, r, c);
if (temp >= A && temp <= B) {
count++;
}
}
}
return count;
}
public int getCount(String[] field, int r, int c) {
int maxR = field.length;
int maxC = field[0].length();
int number = 0;
if (r - 1 >= 0) {
number += getRC(field, r - 1, c);
if (c - 1 >= 0) {
number += getRC(field, r - 1, c - 1);
}
if (c + 1 < maxC) {
number += getRC(field, r - 1, c + 1);
}
}
if (r + 1 < maxR) {
number += getRC(field, r + 1, c);
if (c - 1 >= 0) {
number += getRC(field, r + 1, c - 1);
}
if (c + 1 < maxC) {
number += getRC(field, r + 1, c + 1);
}
}
if (c - 1 >= 0) {
number += getRC(field, r, c - 1);
}
if (c + 1 < maxC) {
number += getRC(field, r, c + 1);
}
return number;
}
public int getRC(String[] field, int r, int c) {
return field[r].charAt(c) - '0';
}
}