LeetCode Solutions

840. Magic Squares In Grid

Time: $O(n^2)$

Space: $O(1)$

			

class Solution {
 public:
  int numMagicSquaresInside(vector<vector<int>>& grid) {
    int ans = 0;

    for (int i = 0; i + 2 < grid.size(); ++i)
      for (int j = 0; j + 2 < grid[0].size(); ++j)
        if (grid[i][j] % 2 == 0 && grid[i + 1][j + 1] == 5)
          ans += isMagic(grid, i, j);

    return ans;
  }

 private:
  int isMagic(const vector<vector<int>>& grid, int i, int j) {
    string s;

    for (const int num : {0, 1, 2, 5, 8, 7, 6, 3})
      s += to_string(grid[i + num / 3][j + num % 3]);

    return string("4381672943816729").find(s) != string::npos ||
           string("9276183492761834").find(s) != string::npos;
  }
};
			

class Solution {
  public int numMagicSquaresInside(int[][] grid) {
    int ans = 0;

    for (int i = 0; i + 2 < grid.length; ++i)
      for (int j = 0; j + 2 < grid[0].length; ++j)
        if (grid[i][j] % 2 == 0 && grid[i + 1][j + 1] == 5)
          if (isMagic(grid, i, j))
            ++ans;

    return ans;
  }

  private boolean isMagic(int[][] grid, int i, int j) {
    String s = new String("");

    for (final int num : new int[] {0, 1, 2, 5, 8, 7, 6, 3})
      s += Integer.toString(grid[i + num / 3][j + num % 3]);

    return new String("4381672943816729").contains(s) ||
           new String("9276183492761834").contains(s);
  }
}
			

class Solution:
  def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
    def isMagic(i: int, j: int) -> int:
      s = "".join(str(grid[i + num // 3][j + num % 3])
                  for num in [0, 1, 2, 5, 8, 7, 6, 3])
      return s in "43816729" * 2 or s in "43816729"[::-1] * 2

    ans = 0

    for i in range(len(grid) - 2):
      for j in range(len(grid[0]) - 2):
        if grid[i][j] % 2 == 0 and grid[i + 1][j + 1] == 5:
          ans += isMagic(i, j)

    return ans