我正在研究 Euler 问题项目,但我对问题 11 的解决方案并不满意。有没有一种方法可以用更少的步骤或更快速地遍历矩阵?或者一般来说,有没有更好的方法来解决它?
numbers.txt 是问题 11 中给出的数字矩阵。
http://projecteuler.net/problem=11
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project {
public static void main(String[] args){
int [][] matrix = new int [20][20];
populateMatrix(matrix, "numbers.txt");
System.out.println( greatestProduct(matrix) );
}
public static long greatestProduct(int [][] matrix){
final int NUMBER = 4;
final int LIMIT = matrix.length - NUMBER;
long max = 0;
for(int i= 0; i < matrix.length; i++){
for(int j= 0; j <= LIMIT; j++){
long diagTrack = 1, diagTrack2 = 1, horTrack = 1, horTrack2 = 1;
int y = j;
int x = i;
int r = matrix.length-i-1;
for(int index =0; index<NUMBER; index++){
if(i <= LIMIT){
diagTrack *= matrix[x][y];
diagTrack2*= matrix[r][y];
x++;
r--;
}
horTrack *= matrix[i][y];
horTrack2*= matrix[y][i];
y++;
}
if(max < diagTrack) max = diagTrack;
if(max < diagTrack2) max = diagTrack2;
if(max < horTrack) max= horTrack;
if(max < horTrack2) max = horTrack2;
}
}
return max;
}
public static void populateMatrix(int [][] matrix, String fileName){
File file = new File(fileName);
try {
Scanner scanner = new Scanner(file);
for(int i= 0; scanner.hasNextLine(); i++) {
String line[] = ( (String) scanner.nextLine() ).split(" ");
for(int j= 0; j < line.length; j++)
matrix[i][j]= Integer.parseInt(line[j].trim() );
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}