题目描述

在这里插入图片描述

一、暴力解

c了20%,会超时,请大佬们看看哪里还能优化

public class Main {
    static int[] result;
    public static void main(String[] args) {
        //拿数据
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] strs = new String[n];
        result = new int[n];
        for (int i = 0; i < n; i++) {
            strs[i] = sc.next();
        }
        //计算完美矩阵数
        for (int i = 1; i <= n; i++) {
            perfect(strs, i);
        }
        //输出结果
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }

    public static void perfect(String[] strs, int n) {
        //只有偶数需要计算
        if (n % 2 == 0) {
            //以(i,j)作为起始位置,扫(i,j)->(i + n, j + n)范围
            for (int i = 0; i <= strs.length - n; i++) {
                for (int j = 0; j <= strs.length - n; j++) {
                    int count_1 = 0;
                    for (int x = i; x < i + n; x++) {
                        for (int y = j; y < j + n; y++) {
                            if (strs[x].charAt(y) == '1') count_1++;
                        }
                    }
                    //计算1的数量
                    if(count_1 == (n * n) / 2) result[n - 1]++;
                }

            }
        }

    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐