Leetcode Note: Go - Check if Matrix Is X Matrix

Check if Matrix Is X-Matrix - LeetCode
https://leetcode.com/problems/check-if-matrix-is-x-matrix/

  • Go 言語で取り組んだメモ

回答

[ Go , Python , C++ ] one pass w/ comments - Check if Matrix Is X-Matrix - LeetCode
https://leetcode.com/problems/check-if-matrix-is-x-matrix/solutions/2260192/go-python-c-one-pass-w-comments/

func checkXMatrix(grid [][]int) bool {
    n := len(grid)
    
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            // check if this is a diagonal
            // because topleft diagonal is pattern 0,0 -> 1,1 -> 2,2 etc
            // and topright diagonal is pattern 0,2 -> 1,1 -> 2,0 etc
            if j == i || j == n-i-1 {
                // make sure non-zero
                if grid[i][j] == 0 {
                    return false
                }
            } else {
                // it's not a diagonal, so lets make sure zero
                if grid[i][j] != 0 {
                    return false
                }
            }
        }
    }
    
    // no problems
    return true
}