首页 > 专题系列 > Java解POJ > POJ 2676 Sudoku [解题报告] Java
2013
11-11

POJ 2676 Sudoku [解题报告] Java

Sudoku

问题描述 :

Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3×3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3×3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.

输入:

The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.

输出:

For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

样例输入:

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

样例输出:

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

解题代码:

//* @author: [email protected]
import java.io.*;
class Main
{
 public static void main(String[] args) throws IOException
 {
  InputStreamReader is=new InputStreamReader(System.in);
  BufferedReader in=new BufferedReader(is);
  int cnt=Integer.parseInt(in.readLine());
  while((cnt--)!=0)
  {
   int[][] p=new int[9][9];
   for(int i=0;i< 9;i++)
   {
	for(int j=0;j< 9;j++)
          p[i][j]=in.read()-'0';
        in.readLine();
   }
   uu(0,0,p);
   for(int i=0;i< 9;i++)
   {
     for(int j=0;j< 9;j++)
	System.out.print(p[i][j]);
     System.out.println();
    }
   }
  }

  public static boolean uu(int a,int b,int[][] p)
  {
   if(b>8)
    {
	a++;
	b=0;
	if(a>8) return true;
    }
    if(p[a][b]!=0)return uu(a,b+1,p);
    int[] uu=new int[10];
    for(int k=0;k< 9;k++)
    {
	uu[p[a][k]]++;
	uu[p[k][b]]++;
    }
    int w=a/3,t=b/3;
    for(int k=w*3;k< w*3+3;k++)
	for(int h=t*3;h< t*3+3;h++)
	   uu[p[k][h]]++;
    for(int k=1;k< 10;k++)
    {
	if(uu[k]!=0) continue;
	p[a][b]=k;
	if(uu(a,b+1,p)) return true;
    }
    p[a][b]=0;
    return false;
   }
}

  1. 有限自动机在ACM中是必须掌握的算法,实际上在面试当中几乎不可能让你单独的去实现这个算法,如果有题目要用到有限自动机来降低时间复杂度,那么这种面试题应该属于很难的级别了。

  2. bottes vernies blanches

    I appreciate the efforts you men and women place in to share blogs on such sort of matters, it was certainly useful. Keep Posting!