LeetCode 840 题解

https://leetcode.com/problems/magic-squares-in-grid/description/

题目大意:在n*m的格子里找到满足 行列对角线和相等的 3*3矩阵的个数。且只能由1-9组成。

解题思路:暴力

class Solution {
    private int judge(int x,int y,int [][] g)
    {
        int[] a = new int[10];
        for(int i=x;i<x+3;i++)
        {
            for(int j=y;j<y+3;j++)
            {
                //System.out.print(g[i][j]+" ");
                if(g[i][j]>=10 || g[i][j]<=0) return 0;
                a[g[i][j]]++;
                if( a[g[i][j]]>1) return 0;
            }
            //System.out.println();
        }

        int sum =-1,tmp=0;
        for(int i=x;i<x+3;i++)
        {
            tmp=0;
            for(int j=y;j<y+3;j++)
            {
                tmp+=g[i][j];
            }
            if(sum==-1) sum=tmp;
            else if(sum!=tmp) return 0;
        }

        for(int j=y;j<y+3;j++)
        {
            tmp=0;
            for(int i=x;i<x+3;i++)
            {
                tmp+=g[i][j];
            }
            if(sum!=tmp) return 0;
        }

        tmp = g[x][y]+g[x+1][y+1]+g[x+2][y+2];
        if(sum!=tmp) return 0;
        tmp = g[x][y+2]+g[x+1][y+1]+g[x+2][y];
        if(sum!=tmp) return 0;

        return 1;
    }
    public int numMagicSquaresInside(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int res=0;
        for(int i=0;i+2<n;i++)
        {
            for(int j=0;j+2<m;j++)
            {
                res+=judge(i,j,grid);
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80484727
今日推荐