从https://www.hackerrank.com/challenges/2d-array
尝试hackerRank Q.import pickle
myDict = {"foo": "bar", "spam": "eggs"}
pickle.dump(myDict, "myFile.py") # Stores object in a file
dictFromFile = pickle.load("myFile.py") # Retrieves object from files
print dictFromFile["spam"] # Prints eggs
如果我运行此程序并输入以下内容作为'arr'的内容 111111 222222 333333 444444 555555 666666
static void Main(String[] args)
{
int[][] arr = new int[6][];
for (int arr_i = 0; arr_i < 6; arr_i++)
{
string[] arr_temp = Console.ReadLine().Split(' ');
arr[arr_i] = Array.ConvertAll(arr_temp, Int32.Parse);
}
int[] sum = new int[6];
List<int> n = new List<int>();
for (int i = 0; i + 2 < arr.Length; i++)
{
for (int j = 0; j + 2 < arr.GetLength(0); j++)
{
sum[j] = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
n.Add(sum[j]);
}
}
Console.WriteLine(n.Max());
}
}
}
答案 0 :(得分:0)
希望以下代码可以帮助您
public class Solution {
private static final int _MAX = 6; // size of matrix
private static final int _OFFSET = 2; // hourglass width
private static int matrix[][] = new int[_MAX][_MAX];
private static int maxHourglass = -63; // initialize to lowest possible sum (-9 x 7)
/** Given a starting index for an hourglass, sets maxHourglass
* @param i row
* @param j column
**/
private static void hourglass(int i, int j){
int tmp = 0; // current hourglass sum
// sum top 3 and bottom 3 elements
for(int k = j; k <= j + _OFFSET; k++){
tmp += matrix[i][k];
tmp += matrix[i + _OFFSET][k];
}
// sum middle element
tmp += matrix[i + 1][j + 1];
if(maxHourglass < tmp){
maxHourglass = tmp;
}
}
public static void main(String[] args) {
// read inputs
Scanner scan = new Scanner(System.in);
for(int i=0; i < _MAX; i++){
for(int j=0; j < _MAX; j++){
matrix[i][j] = scan.nextInt();
}
}
scan.close();
// find maximum hourglass
for(int i=0; i < _MAX - _OFFSET; i++){
for(int j=0; j < _MAX - _OFFSET; j++){
hourglass(i, j);
}
}
// print maximum hourglass
System.out.println(maxHourglass);
}
}