• 36. Valid Sudoku


    36. Valid Sudoku

    题目

    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.
    
    

    解析

    • 只是检测每行,每列,每个小方格是否满足九宫格的定义;使用hash表节省空间
    • 另外就是小方格的坐标转换[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]需要技巧
    // 36. Valid Sudoku 数独/九宫格问题
    class Solution_36 {
    public:
    	bool isValidSudoku(vector<vector<char>>& board) {
    
    		int row = board.size();
    		int col = board[0].size();
    
    		unordered_map<char,int> row_mp; // <char, bool>
    		unordered_map<char,int> col_mp;
    		unordered_map<char, int>  diagonal; //对角线; sub-boxes
    
    		for (int i = 0; i < row;i++)
    		{
    			for (int j = 0; j < col;j++)
    			{
    				if (board[i][j]!='.' && row_mp.find(board[i][j])!=row_mp.end())
    				{
    					return false; //已经存在
    				}
    				else
    				{
    					row_mp[board[i][j]]++;
    				}
    				if (board[j][i] != '.'&& col_mp.find(board[j][i]) != col_mp.end())
    				{
    					return false;
    				}
    				else
    				{
    					col_mp[board[j][i]]++;
    				}
    				if (board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] != '.'&& diagonal.find(board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]) != diagonal.end()) // //第i个九宫格第j个格子
    				{
    					return false;
    				}
    				else
    				{
    					diagonal[board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]]++;
    				}
    			}
    			col_mp.clear();
    			row_mp.clear();
    			diagonal.clear();
    		}
    		return true;
    	}
    };
    

    题目来源

  • 相关阅读:
    转: java语法与ide级入门介绍 from: IBM dev
    Java Servlet 技术简介 from:IBM Dev
    腾讯开源组件-毫秒服务引擎
    JS中的slice和splice
    validform校验框架不显示错误提示
    jQuery获取不到隐藏DIV的高度和宽度
    前端页面下载
    Java传统下载和SpringMVC下载
    先尽人事,再听天命
    Java生成PDF之iTextPDF的使用
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8397845.html
Copyright © 2020-2023  润新知