leetCode练习(36)

题目:Valid Sudoku

难度:easy

问题描述:

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.

解题思路:

问题的关键在于约束是什么,数独是否有效有三点需要判断:

1.每一横行没有重复数字。

2.每一纵行没有重复数字。

3.每一九宫格没有重复数字。

可以实现一个函数 isnotchongfu(char[] c)来判断输入的九个数是否重复。接下来就是找到所有需要判别的字符数组即可。

具体代码如下:

public class Solution {
    	int[]temp=new int[9];
	char[]temp2=new char[9];
	char c;
    	public boolean isValidSudoku(char[][] board) {
        //横向不重复
        System.out.println("你好");
		int i,j,k=0;
		for(i=0;i<9;i++){
			if(!isnotchongfu(board[i])){
				return false;
			}
		}
		System.out.println("heng");
		
		//3*3不重复
		for(i=0;i<3;i++){
			for(j=0;j<3;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=0;i<3;i++){
			for(j=3;j<6;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=0;i<3;i++){
			for(j=6;j<9;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=3;i<6;i++){
			for(j=0;j<3;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=3;i<6;i++){
			for(j=3;j<6;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=3;i<6;i++){
			for(j=6;j<9;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=6;i<9;i++){
			for(j=0;j<3;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=6;i<9;i++){
			for(j=3;j<6;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		
		for(i=6;i<9;i++){
			for(j=6;j<9;j++){
				temp2[k++]=board[i][j];
			}
		}
		if(!isnotchongfu(temp2)){
			return false;
		}
		k=0;
		//纵向不重复
		for(i=0;i<9;i++){	//反置
			for(j=i;j<9;j++){
				c=board[i][j];
				board[i][j]=board[j][i];
				board[j][i]=c;
			}
		}
		for(i=0;i<9;i++){
			if(!isnotchongfu(board[i])){
				return false;
			}
		}
		System.out.println("zong");
		return true;
    }
    public  boolean isnotchongfu(char[] nums){
        for(int j=0;j<9;j++){
			temp[j]=0;
		}
		for(int i=0;i<9;i++){
			c=nums[i];
			if(c!='.'){
				if(temp[(int)(c-'1')]==0){
					temp[(int)(c-'1')]++;
				}else{
					return false;
				}
			}
		}
		return true;	
	}
}
对于3*3的9个数的取值,我还没有方便的方法,希望大家的指正!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值