码迷,mamicode.com
首页 > 其他好文 > 详细

148.Magic Squares In Grid

时间:2018-09-08 14:12:53      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:rom   private   each   numbers   gic   only   grid   resin   ali   

题目:

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

标签:rom   private   each   numbers   gic   only   grid   resin   ali   

原文地址:https://www.cnblogs.com/chanaichao/p/9608829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!