[LeetCode] 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).

 

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
 

這道題定義了一種神奇正方形,是一個3x3大小,且由1到9中到數字組成,各行各列即對角線和都必須相等。那么其實這個神奇正方形的各行各列及對角線之和就已經被限定了,必須是15才行,而且最中間的位置必須是5,否則根本無法組成滿足要求的正方形。博主也沒想出啥特別巧妙的方法,就老老實實的遍歷所有的3x3大小的正方形唄,我們寫一個子函數來檢測各行各列及對角線的和是否為15,在調用子函數之前,先檢測一下中間的數字是否為5,是的話再進入子函數。在子函數中,先驗證下該正方形中的數字是否只有1到9中的數字,且不能由重復出現,使用一個一維數組來標記出現過的數字,若當前數字已經出現了,直接返回true。之后便是一次計算各行各列及對角線之和是否為15了,若全部為15,則返回true,參見代碼如下:

 

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;
    }
};

 

參考資料:

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

 

LeetCode All in One 題目講解匯總(持續更新中...) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM