问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3752 访问。

3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。

给定一个由整数组成的 m * n 矩阵,其中有多少个 3 × 3 的 “幻方” 子矩阵?(每个子矩阵都是连续的)。

输入: [[4,3,8,4],

      [9,5,1,9],

      [2,7,6,2]]

输出: 1

解释: 

下面的子矩阵是一个 3 x 3 的幻方:

438

951

276

而这一个不是:

384

519

762

总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。

提示:

1 <= grid.length = grid[0].length <= 10

0 <= grid[i][j] <= 15


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).

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 <= grid.length <= 10

1 <= grid[0].length <= 10

0 <= grid[i][j] <= 15


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3752 访问。

public class Program {

    public static void Main(string[] args) {
int[][] nums = null; nums = new int[3][] {new int[]{4,3,8,4},
new int[] {9,5,1,9},
new int[] {2,7,6,2}
}; var res = NumMagicSquaresInside(nums);
Console.WriteLine(res); nums = new int[3][] {new int[]{1,0,3,8},
new int[] {3,7,2,4},
new int[] {5,8,1,0}
}; res = NumMagicSquaresInside2(nums);
Console.WriteLine(res); Console.ReadKey();
} private static int NumMagicSquaresInside(int[][] grid) {
var num = 0;
for(var i = 1; i < grid.Length - 1; i++) {
for(var j = 1; j < grid[i].Length - 1; j++) {
if(grid[i][j] == 5) {
num = IsMagicSquare(grid, i, j) ? ++num : num;
}
}
}
return num;
} private static bool IsMagicSquare(int[][] grid, int i, int j) {
//原始解法,不推荐
//记录每个值,看是不是9位,因为从1-9都必须出现
var dic = new Dictionary<int, int>();
dic[grid[i - 1][j - 1]] = grid[i - 1][j - 1];
dic[grid[i - 1][j]] = grid[i - 1][j];
dic[grid[i - 1][j + 1]] = grid[i - 1][j + 1]; dic[grid[i][j - 1]] = grid[i][j - 1];
dic[grid[i][j]] = grid[i][j];
dic[grid[i][j + 1]] = grid[i][j + 1]; dic[grid[i + 1][j - 1]] = grid[i + 1][j - 1];
dic[grid[i + 1][j]] = grid[i + 1][j];
dic[grid[i + 1][j + 1]] = grid[i + 1][j + 1]; //不为9或不在1-9范围之内,则不是幻方
if(dic.Count != 9) return false; foreach(var item in dic) {
if(item.Value > 9 || item.Value < 0) return false;
} //记录3行、3列、2对角线
var sum_row1 = grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1];
var sum_row2 = grid[i][j - 1] + grid[i][j] + grid[i][j + 1];
var sum_row3 = grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1]; var sum_col1 = grid[i - 1][j - 1] + grid[i][j - 1] + grid[i + 1][j - 1];
var sum_col2 = grid[i - 1][j] + grid[i][j] + grid[i + 1][j];
var sum_col3 = grid[i - 1][j + 1] + grid[i][j + 1] + grid[i + 1][j + 1]; var sum_cross1 = grid[i - 1][j - 1] + grid[i][j] + grid[i + 1][j + 1];
var sum_cross2 = grid[i - 1][j + 1] + grid[i][j] + grid[i + 1][j - 1]; var dic2 = new Dictionary<int, int>();
dic2[sum_row1] = 0;
dic2[sum_row2] = 0;
dic2[sum_row3] = 0; dic2[sum_col1] = 0;
dic2[sum_col2] = 0;
dic2[sum_col3] = 0; dic2[sum_cross1] = 0;
dic2[sum_cross2] = 0; //看值是不是相同并且值之和为15
return dic2.Count == 1 && sum_row1 == 15;
} private static int NumMagicSquaresInside2(int[][] grid) {
var num = 0;
for(var i = 1; i < grid.Length - 1; i++) {
for(var j = 1; j < grid[i].Length - 1; j++) {
if(grid[i][j] == 5) {
num = IsMagicSquare(grid, i, j) ? ++num : num;
}
}
}
return num;
} private static bool IsMagicSquare2(int[][] grid, int row, int col) {
//值必须是1-9
for(var i = row - 1; i <= row + 1; i++)
for(var j = col - 1; j <= col + 1; j++)
if(grid[i][j] < 1 || grid[i][j] > 9) return false;
//不考虑中间的5,只需要考虑4个位置的值的和为10即可
return !(grid[row - 1][col - 1] + grid[row + 1][col + 1] != 10 ||
grid[row - 1][col] + grid[row + 1][col] != 10 ||
grid[row - 1][col + 1] + grid[row + 1][col - 1] != 10 ||
grid[row][col - 1] + grid[row][col + 1] != 10);
} }

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3752 访问。

1
0

分析:

显而易见,以上2种算法的时间复杂度均为:  。

C#LeetCode刷题之#840-矩阵中的幻方(Magic Squares In Grid)的更多相关文章

  1. [Swift]LeetCode840. 矩阵中的幻方 | 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, co ...

  2. leetcode刷题-54螺旋矩阵

    题目 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 思路 对于每个外层,从左上方开始以顺时针的顺序遍历所有元素.假设当前层的左上角位于(to ...

  3. Leetcode刷题之螺旋矩阵

    矩阵之螺旋矩阵 总体思路: 注意遍历顺序 每次遍历一圈时候不要多加元素 Leetcode54螺旋矩阵 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素. ...

  4. leetcode刷题-59螺旋矩阵2

    题目 给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵. 思路 与螺旋矩阵题完全一致 实现 class Solution: def generateM ...

  5. C#LeetCode刷题之#671-二叉树中第二小的节点(Second Minimum Node In a Binary Tree)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4100 访问. 给定一个非空特殊的二叉树,每个节点都是正数,并且每 ...

  6. C#LeetCode刷题之#532-数组中的K-diff数对(K-diff Pairs in an Array)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3716 访问. 给定一个整数数组和一个整数 k, 你需要在数组里找 ...

  7. C#LeetCode刷题之#720-词典中最长的单词(Longest Word in Dictionary)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4120 访问. 给出一个字符串数组words组成的一本英语词典.从 ...

  8. leetcode刷题-94二叉树的中序遍历

    题目 给定一个二叉树,返回它的中序 遍历. 实现 # def __init__(self, x): # self.val = x # self.left = None # self.right = N ...

  9. C#LeetCode刷题-数组

    数组篇 # 题名 刷题 通过率 难度 1 两数之和 C#LeetCode刷题之#1-两数之和(Two Sum) 43.1% 简单 4 两个排序数组的中位数 C#LeetCode刷题之#4-两个排序数组 ...

随机推荐

  1. java面试题jvm字节码的加载与卸载

    虚拟机把描述类的数据从class文件加载到内存,并对数据进行校验,转换分析和初始化,最终形成可以被虚拟节直接使用的JAVA类型,这就是虚拟机的类加载机制. 类从被加载到虚拟机内存到卸载出内存的生命周期 ...

  2. 一文快速掌握华为云IPv6基础知识及使用指南

    随着5G.物联网等新兴技术领域的发展,IP空间需求巨大,IPv6成为万物互联的基础,势在必行:华为云作为IPv6成熟商用开拓者,针对金融.广电.媒资等不同行业推出IPv6解决方案,助力企业平滑升级到I ...

  3. Web Scraping using Python Scrapy_BS4 - Introduction

    What is Web Scraping This is also referred to as web harvesting and web data extraction. This is the ...

  4. P3406 海底高铁 (洛谷)

    题目背景 大东亚海底隧道连接着厦门.新北.博艾.那霸.鹿儿岛等城市,横穿东海,耗资1000亿博艾元,历时15年,于公元2058年建成.凭借该隧道,从厦门可以乘坐火车直达台湾.博艾和日本,全程只需要4个 ...

  5. ffmpeg拉流长时间堵塞解决方式

    由于网络堵塞或者推流端错误导致拉流端没有流数据,ffmpeg主要会堵塞两个函数,直到下次流数据的到来 avformat_open_input() 该函数是在打开流数据时,如果没有这个流的ip,http ...

  6. 关于maven的一份小笔记

    简介 项目里一直用的 maven,几乎天天和这个"熟知"的工具打交道,但是,最近我发觉自己对 maven 了解的还不够,例如,什么是 goal?什么是 phase?等等.趁着最近有 ...

  7. DJANGO-天天生鲜项目从0到1-013-订单-支付宝支付

    本项目基于B站UP主‘神奇的老黄’的教学视频‘天天生鲜Django项目’,视频讲的非常好,推荐新手观看学习 https://www.bilibili.com/video/BV1vt41147K8?p= ...

  8. sed 指定行范围匹配

    sed -n '5,10{/pattern/p}' file sed是一个非交互性性文本编辑器,它编辑文件或标准输入 导出的文件拷贝.标准输入可能是来自键盘.文件重定向.字符串或变量,或者是一个管道文 ...

  9. Android集成JPush(极光推送)

    目前只是简单的集成 1.在极光推送官网注册用户 2.创建应用 3.配置包名,获得APPKEY 去设置 输入应用包名 确定然后返回查看APPKEY 3.在应用中集成极光推送 用的jcenter自动集成的 ...

  10. 大家是怎么做APP接口的版本控制的?欢迎进来看看我的方案。升级版的Versioning

    背景 APP不同于网站,网站程序一发版,所有用户看到的都是最新的页面.调用最新的接口,没有新老版本一说.APP一旦下载到用户手机上,用户不更新你拿他一点办法都没有,但是随着业务的调整,同一个接口的请求 ...