Skip to content

Instantly share code, notes, and snippets.

@stephenjtong
Last active December 13, 2015 20:29
Show Gist options
  • Save stephenjtong/4970576 to your computer and use it in GitHub Desktop.
Save stephenjtong/4970576 to your computer and use it in GitHub Desktop.
暴力解数独 force brute to solve a Sudoku
//数独
import java.util.*;
public class Sudoku{
private static int steps=0;
private static int sudo[][]=new int[][]{
{0,0,0,0,0,9,6,0,0},
{0,0,7,0,0,1,0,0,0},
{0,4,0,0,0,0,0,0,0},
{0,0,0,0,4,0,0,0,0},
{0,2,0,8,0,0,0,0,0},
{0,1,6,0,0,0,7,0,0},
{0,0,5,0,0,7,0,0,0},
{0,0,0,0,0,0,0,2,0},
{0,0,3,0,0,0,0,4,8}};
public static void main(String[] args) {
if(cacu(0,0))
dis();
else
System.out.println("No results.");
}
private static void dis()
{
for(byte a=0;a<9;a++)
{
for(byte b=0;b<9;b++)
{
System.out.print(sudo[a][b]);
}
System.out.println();
}
System.out.println("Steps: "+steps);
}
private static boolean cacu(int i,int j)
{
steps++;
boolean flag=true;
if(sudo[i][j]!=0)
{
j++;
if(j==9)
{
j=0;
i++;
}
if(i==9) return true;
return cacu(i,j);
}
for(int k=1;k<10;k++)
{
flag=true;
for(int m=0;m<9;m++)
{
if(m==j)continue;
if(sudo[i][m]==k)
{
flag=false;
break;
}
}
if(flag==false)continue;
for(int m=0;m<9;m++)
{
if(m==i)continue;
if(sudo[m][j]==k)
{
flag=false;
break;
}
}
if(flag==false)continue;
for(int b=i-(i%3);b<i-(i%3)+3;b++)
for(int a=j-(j%3);a<j-(j%3)+3;a++)
{
if(b==i&&a==j)continue;
if(sudo[b][a]==k)
{
flag=false;
break;
}
}
if(flag==false&&k!=9)continue;
if(flag==true){ sudo[i][j]=k;
}
j++;
if(j==9)
{
j=0;
i++;
}
if(i==9) return true;
if(cacu(i,j))
return true;
else
{
if(j==0)
{
j=8;
i--;
}
else
j--;
}
}
sudo[i][j]=0;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment