用暴力求範圍小的最大子陣

給定一個n*m的矩陣A, 求A中的一個非空子矩陣,使這個子矩陣中的元素和最大。
輸入:輸入的第一行包含兩個整數n,m(1<=n, m<=50),分別表示矩陣A的行數和列數,接下來n行 每行m個整數,矩陣Aij(-1000<=Aij<=1000)。
樣例輸入:
3 3
2 -4 1
-1 2 1
4 -2 2
樣例輸出:
6

代碼:

import java.util.Scanner;

public class Main {
    private static int[][] a;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        a = new int[n+1][m+1];
        for(int i = 0; i < n; i ++) {
            for(int j = 0; j < m; j ++) {
                a[i][j] = scan.nextInt();
            }
        }
        int max = -1001;//這裏要注意
        for(int i = 0; i < n; i ++) {
            for(int j = 0; j < n; j ++) {
                for(int k = i; k < n; k ++) {
                    for(int l = j; l < m; l ++) {
                        max = Math.max(max, fun(i, j, k, l));
                    }
                }
            }
        }
        System.out.println(max);
    }

    public static int fun(int x1, int y1, int x2, int y2) {
        int sum = 0;
        for(int i = x1; i <= x2; i ++) {
            for(int j = y1; j <= y2; j ++) {
                sum += a[i][j];
                //System.out.println(sum);
            }
        }

        return sum;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章