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.html
Given an grid
of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).數組
Example 1:ide
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
這道題定義了一種神奇正方形,是一個3x3大小,且由1到9中到數字組成,各行各列即對角線和都必須相等。那麼其實這個神奇正方形的各行各列及對角線之和就已經被限定了,必須是15才行,並且最中間的位置必須是5,不然根本沒法組成知足要求的正方形。博主也沒想出啥特別巧妙的方法,就老老實實的遍歷全部的3x3大小的正方形唄,咱們寫一個子函數來檢測各行各列及對角線的和是否爲15,在調用子函數以前,先檢測一下中間的數字是否爲5,是的話再進入子函數。在子函數中,先驗證下該正方形中的數字是否只有1到9中的數字,且不能由重複出現,使用一個一維數組來標記出現過的數字,若當前數字已經出現了,直接返回true。以後即是一次計算各行各列及對角線之和是否爲15了,若所有爲15,則返回true,參見代碼以下:post
class Solution { public: int numMagicSquaresInside(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(), res = 0; for (int i = 0; i < m - 2; ++i) { for (int j = 0; j < n - 2; ++j) { if (grid[i + 1][j + 1] == 5 && isValid(grid, i, j)) ++res; } } return res; } bool isValid(vector<vector<int>>& grid, int i, int j) { vector<int> cnt(10); for (int x = i; x < i + 2; ++x) { for (int y = j; y < j + 2; ++y) { int k = grid[x][y]; if (k < 1 || k > 9 || cnt[k] == 1) return false; cnt[k] = 1; } } if (15 != grid[i][j] + grid[i][j + 1] + grid[i][j + 2]) return false; if (15 != grid[i + 1][j] + grid[i + 1][j + 1] + grid[i + 1][j + 2]) return false; if (15 != grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2]) return false; if (15 != grid[i][j] + grid[i + 1][j] + grid[i + 2][j]) return false; if (15 != grid[i][j + 1] + grid[i + 1][j + 1] + grid[i + 2][j + 1]) return false; if (15 != grid[i][j + 2] + grid[i + 1][j + 2] + grid[i + 2][j + 2]) return false; if (15 != grid[i][j] + grid[i + 1][j + 1] + grid[i + 2][j + 2]) return false; if (15 != grid[i + 2][j] + grid[i + 1][j + 1] + grid[i][j + 2]) return false; return true; } };
參考資料:this
https://leetcode.com/problems/magic-squares-in-grid/url