最大子矩阵
题目:求一个矩阵中最大2*2矩阵(元素和最大)的和。
如:
1 2 3 0 4
2 3 4 5 1
1 1 5 3 0
中最大的是
4 5
5 3
和为17
输入:m*n的矩阵
输出:该m*n矩阵的最大2*2子矩阵的和。
例如输入:
1 2 0 3 4 ; 2 3 4 5 1; 1 1 5 3 0
输出:
17
分析:这道题目是一道OJ的题目,原题是求最大子矩阵的和,题目里子矩阵是随意的,没有2*2的限制。这里2*2子矩阵是将问题简化了。最蛋疼的是,问题的输入格式太奇葩,大部分时间都花在调这个输入格式上了!!!最简单的方法是对矩阵进行遍历,得到最大子矩阵的和即可。
package com.didi;
import java.util.Scanner;
/**
* Created by fang on 2015/9/25.
*/
class Solution {
public int maxSubMatrix(int[][] matrix) {
int result = Integer.MIN_VALUE;
for (int i = 0; i < matrix.length - 1; i++) {
for (int j = 0; j < matrix[0].length - 1; j++) {
int tempSum = matrix[i][j] + matrix[i][j + 1] + matrix[i + 1][j] + matrix[i + 1][j + 1];
result = Math.max(result, tempSum);
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] lines = line.split(";");
int row = lines.length;
String[] line2 = line.split(" ");
int col = (line2.length - row + 1) / row;
int[][] matrix = new int[row][col];
for (int i = 0; i < row; i++) {
String str = lines[i];
String[] temp = str.split(" ");
int k = 0;
for (int j = 0; j < temp.length; j++) {
if (!temp[j].equals(" ") && !temp[j].equals("")) {
matrix[i][k++] = Integer.parseInt(temp[j]);
}
}
}
Solution sln = new Solution();
int result = sln.maxSubMatrix(matrix);
System.out.println(result);
}
}
原文:http://www.cnblogs.com/fangying7/p/4840429.html