Skip to content

Instantly share code, notes, and snippets.

@johobemax
Created June 25, 2010 04:06
Show Gist options
  • Save johobemax/452390 to your computer and use it in GitHub Desktop.
Save johobemax/452390 to your computer and use it in GitHub Desktop.
public class Sudoku{
private int[][] field =
{
{3,6,0,8,9,0,0,0,2},
{9,0,0,0,5,2,3,0,0},
{7,0,0,0,0,1,9,8,4},
{8,0,0,2,4,0,0,0,6},
{2,5,3,0,7,6,0,9,8},
{0,0,6,0,0,0,0,0,0},
{0,0,7,5,0,8,0,0,9},
{0,4,0,9,0,3,0,0,5},
{0,0,0,0,6,7,0,0,0}
};
private int count = 1;
public Sudoku(){
}
public void view(){
for(int i=0; i<9; i++){
if(i%3==0)
System.out.println("+------+------+------+");
for(int j=0; j<9; j++){
if(j%3==0)
System.out.print("|");
System.out.print(" " + (field[i][j]>0?field[i][j]:" "));
}
System.out.println("|");
}
System.out.println("+------+------+------+");
}
public void go(int p){
if(p==81){
System.out.println("正解"+count);
view();
count++;
return;
}
if(field[p/9][p%9]==0){
for(int i=1; i<=9; i++){
int flg = 0;
for(int j=0; j<9; j++){
if(field[j][p%9]==i){
flg = 1;
break;
}
}
for(int j=0; j<9; j++){
if(field[p/9][j]==i){
flg = 1;
break;
}
}
for(int j=0; j<9; j++){
if(field[(p/27)*3+j%3][((p%9)/3)*3+j/3]==i){
flg = 1;
break;
}
}
if(flg==0){
field[p/9][p%9] = i;
go(p+1);
field[p/9][p%9] = 0;
}
}
field[p/9][p%9] = 0;
}else{
go(p+1);
}
}
public static void main(String args[]){
Sudoku s = new Sudoku();
s.view();
s.go(0);
}
}
@johobemax
Copy link
Author

数独の問題を解くプログラム

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment