zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

    The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


    A partially filled sudoku which is valid.

    Note:
    A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

    思路:

    先验证每一行,再验证每一列,再验证每一个小正方形。

    package sudoku;
    
    public class ValidSudoku {
    
        public boolean isValidSudoku(char[][] board) {
            int n = 9;
            for (int i = 0; i < n; ++i) {
                int[] arr = new int[10];
                for (int j = 0; j < n; ++j) {
                    if (board[i][j] != '.')
                        arr[board[i][j] - '0']++;
                }
                if (!validate(arr))
                    return false;
            }
            
            for (int i = 0; i < n; ++i) {
                int[] arr = new int[10];
                for (int j = 0; j < n; ++j) {
                    if (board[j][i] != '.')
                        arr[board[j][i] - '0']++;
                }
                if (!validate(arr))
                    return false;
            }
            
            for (int i = 0; i < n; i += 3) {
                for (int j = 0; j < n; j += 3) {
                    int[] arr = new int[10];
                    for (int x = i; x < i + 3; ++x) {
                        for (int y = j; y < j + 3; ++y) {
                            if (board[x][y] != '.') 
                                arr[board[x][y] - '0']++;
                        }
                    }
                    if (!validate(arr))
                        return false;
                }
            }
            
            return true;
        }
        
        private boolean validate(int[] arr) {
            for (int i = 1; i < 10; ++i) {
                if (arr[i] > 1)
                    return false;
            }
            return true;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
        }
    
    }
  • 相关阅读:
    My first blog!
    Elasticsearch安装 + Head插件安装 + Bigdesk插件安装
    泛型-反射-注解
    JFinal自定义FreeMarker标签
    Hadoop集群中节点角色定义
    HBase
    MapReduce
    HDFS
    Hadoop基本概念
    HTTP浅析
  • 原文地址:https://www.cnblogs.com/null00/p/5068732.html
Copyright © 2011-2022 走看看