實現數獨小例子

 

package shudutianshu;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;


public class shudu{


  // 隨機數,返回1-9的隨機數
  public static Integer getRandom() {
   return (int) (Math.random() * 9) + 1;
  }

  // 找到一個可填充的數;
  public static int getNumber(int[][] array, int[] pos) {
   
   List<Integer> list = new ArrayList<Integer>(9);// 如果1-9全不合要求,表示寫入失敗;

   int n = 0;
   do{
    n = getRandom();

    if (list.size() == 9)
     throw new RuntimeException();// 失敗;
    if (!list.contains(n))
     list.add(n);
   }while (!(checkRow(array, pos, n) && checkCol(array, pos, n) && checkArea(
     array, pos, n)));

   return n;
  }

  // 檢查行,有重複的,返回false
  public static boolean checkRow(int[][] array, int[] pos, int number) {
   int row = pos[0];
   for (int i = 0; i < pos[1]; i++) {
    if (i != pos[1] && number == array[row][i]) {
     return false;
    }
   }

   return true;
  }

  // 檢查列,有重複的,返回false
  public static boolean checkCol(int[][] array, int[] pos, int number) {
   int col = pos[1];
   for (int i = 0; i < pos[0]; i++) {
    if (i != pos[0] && number == array[i][col])
     return false;
   }
   return true;
  }

  // 檢查所在的小區域,有重複的,返回false
  public static boolean checkArea(int[][] array, int[] pos, int number) {
   int row = pos[0] / 3 * 3;// 所在區域左上角行座標
   int col = pos[1] / 3 * 3;// 所在區域左上角列座標
   for (int i = row; i < row + 3; i++)
    for (int j = col; j < col + 3; j++) {
     if (!(pos[0] == i && pos[1] == j) && (array[i][j] == number))// 檢查時不包含自身位置
      return false;
    }
   return true;
  }

  // 產生一個數獨;
  public static int[][] createSudoku() {

   boolean flag = true;
   int[][] array = null;

   int count = 0;// 一共要寫多少次才能寫成功;

   while (flag) {
    try {
     count++;
     array = new int[9][9];
     for (int i = 0; i < 9; i++) {
      for (int j = 0; j < 9; j++) {
       int[] pos = { i, j };
       array[i][j] = getNumber(array, pos);
      }
     }
     flag = false;// 填寫完成時,終止while循環;
    } catch (RuntimeException e) {
    }
   }
   System.out.println("total try : " + count);
   return array;
  }

  @Test
  public void testNumberFactory() {
   for (int i = 0; i < 1000; i++) {
    int n = getRandom();
    if (n < 1 || n > 9)
     System.out.println(n);
   }
  }

  @Test
  public void test() {
   int[][] array = new int[9][9];
   long time1 = System.currentTimeMillis();
   array = createSudoku();
   System.out.println("total time: "
     + (System.currentTimeMillis() - time1));
   for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
     System.out.print(array[i][j] + " ");
    }
    System.out.println();
   }
  }
  
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章