1. 程式人生 > >leetcode (Magic Squares In Grid)

leetcode (Magic Squares In Grid)

Title:Magic Squares In Grid   840

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/magic-squares-in-grid/

 

1.  基本方法,主要中間的數值必須為5

時間複雜度:O(n^2),巢狀for迴圈,需要遍歷整個陣列。

空間複雜度:O(n),申請長度為16的陣列。

    /**
     * 注意中間的數值必須為5
     * @param grid
     * @return
     */
    public static int numMagicSquaresInside(int[][] grid) {

        int rowLength = grid.length;
        int columnLength = grid[0].length;
        int count = 0;

        for (int i = 0; i < rowLength - 2; i++) {
            for (int j = 0; j < columnLength - 2; j++) {
                if (grid[i + 1][j + 1] != 5) {
                    continue;
                }
                if (magic (grid[i][j], grid[i][j + 1], grid[i][j + 2],
                            grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2],
                            grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2])) {
                    count++;
                }
            }
        }

        return count;

    }

    private static boolean magic(int ... grids) {

        int tmp[] = new int[16];
        for (int value : grids) {
            tmp[value]++;
        }
        for (int i = 1; i <= 9; i++) {
            if (tmp[i] != 1) {
                return false;
            }
        }

        return (grids[0] + grids[1] + grids[2] == 15 &&
                grids[3] + grids[4] + grids[5] == 15 &&
                grids[6] + grids[7] + grids[8] == 15 &&
                grids[0] + grids[3] + grids[6] == 15 &&
                grids[1] + grids[4] + grids[7] == 15 &&
                grids[2] + grids[5] + grids[8] == 15 &&
                grids[0] + grids[4] + grids[8] == 15 &&
                grids[2] + grids[4] + grids[6] == 15);

    }