码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_36题——Valid Sudoku()

时间:2015-05-01 13:13:48      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

Valid Sudoku

 Total Accepted: 33447 Total Submissions: 122453My Submissions

 

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.

 

Hide Tags
 Hash Table
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

    这道题求的是就宫格是否是有效的,只是对于已经填好的数字,而不是有没有解的问题,这里需要考虑的是每一行每一列,还有每一个九宫格是否在已经填的数字中出现

了重复,所以想到的是两重循环,依次的往下遍历,而在这个过程中又三个判断,而采用三个数组来记录,行,列,九宫格,而这里九宫格是采用将i,j转换成第几个九宫格

#include<iostream>
#include<vector>
using namespace std;

int flag1[10];
int flag2[10][10];
int flag3[10][10];


int changeij(int i,int j)
{
	int result;
	if(i<=2)
		result=j/3;
	else if(i>2&&i<=5)
		result=3+j/3;
	else
		result=6+j/3;

	return result;
}
bool isValidSudoku(vector<vector<char>>& board) {
	memset(flag2,0,sizeof(flag2));
	memset(flag3,0,sizeof(flag3));

	for(int i=0;i!=9;i++)
	{
		memset(flag1,0,sizeof(flag1));
		for(int j=0;j!=9;j++)
		{
			if(board[i][j]!=‘.‘)
			{
				if(flag1[board[i][j]-48]==1)
					return false;
				else
					flag1[board[i][j]-48]=1;

				if(flag2[board[i][j]-48][j]==1)
					return false;
				else
					flag2[board[i][j]-48][j]=1;

				if(flag3[changeij(i,j)][board[i][j]-48]==1)
					return false;
				else
					flag3[changeij(i,j)][board[i][j]-48]=1;
			}
		}
	}
	return true;
}
int main()
{
	vector<vector<char> > vec=["....5..1.",".4.3.....",".....3..1","8......2.","..2.7....",".15......",".....2...",".2.9.....","..4......"];
	cout<<changeij(4,2)<<endl;
}

  

 

leetcode_36题——Valid Sudoku()

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4470542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!