148.Magic Squares In Grid

Posted chanaichao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了148.Magic Squares In Grid相关的知识,希望对你有一定的参考价值。

题目:

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

Given an grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).

3 x 3魔方是一个3 x 3网格,填充了从1到9的不同数字,这样每行,每列和两个对角线都具有相同的总和。给定一个整数网格,有多少个3 x 3“魔方”子网格? (每个子网格都是连续的)。

 

Example 1:

Input: [[4,3,8,4],
        [9,5,1,9],
        [2,7,6,2]]
Output: 1
Explanation: 
The following subgrid is a 3 x 3 magic square:
438
951
276

while this one is not:
384
519
762

In total, there is only one magic square inside the given grid.

Note:

  1. 1 <= grid.length <= 10
  2. 1 <= grid[0].length <= 10
  3. 0 <= grid[i][j] <= 15

解答:

 1 class Solution {
 2     public int numMagicSquaresInside(int[][] grid) {
 3         int cnt=0;
 4         for(int i=0;i<=grid.length-3;i++)
 5             for(int j=0;j<=grid[0].length-3;j++)
 6                 if(helper(i,j,grid)) cnt++;
 7             
 8         return cnt;
 9     }  
10     
11     private boolean helper(int x,int y,int[][] grid){
12         if(grid[x+1][y+1]!=5) return false;
13         
14         int[] valid=new int[16];
15         
16         for(int i=x;i<=x+2;i++)
17             for(int j=y;j<=y+2;j++)
18                 valid[grid[i][j]]++;
19             
20         for (int v = 1; v <= 9; v++)
21             if (valid[v] != 1) return false;
22         
23         if((grid[x][y]+grid[x][y+1]+grid[x][y+2])!=15)         return false;
24         if((grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2])!=15)     return false;
25         if((grid[x][y]+grid[x+1][y]+grid[x+2][y])!=15)         return false;
26         if((grid[x+2][y]+grid[x+2][y+1]+grid[x+2][y+2])!=15)   return false;
27         if((grid[x][y+2]+grid[x+1][y+2]+grid[x+2][y+2])!=15)   return false;
28         if((grid[x][y+2]+grid[x+1][y+1]+grid[x+2][y])!=15)     return false;
29         return true;
30     }
31 }

详解:

 

以上是关于148.Magic Squares In Grid的主要内容,如果未能解决你的问题,请参考以下文章

840. Magic Squares In Grid ——weekly contest 86

Leetcode_easy840. Magic Squares In Grid

[LeetCode] 840. Magic Squares In Grid_Easy

840. Magic Squares In Grid (5月27日)

Leetcode 840. Magic Squares In Grid

425. Word Squares