数独与AC3

时间:2013-08-01 21:17:26

标签: java algorithm sudoku backtracking

我正在尝试在java中实现数独问题。目前我已经设法实现了回溯的天真实现,它似乎正在工作,但我需要的是使用AC3算法。我在几个来源上看到了它的伪代码:http://en.wikipedia.org/wiki/AC-3_algorithm(一个例子),我想知道什么是限制。

function arc-reduce (x, y)
 bool change = false
 for each vx in D(x)
     find a value vy in D(y) such that vx and vy satisfy the constraint R2(x, y)
     if there is no such vy {
         D(x) := D(x) - vx
         change := true
     }
 return change

更具体地说,我将X,Y作为2个节点发送:

class Node{
 int i,j;
}

每个节点都包含我的数独表中元素的坐标。但是我对R2约束使用了什么?

我目前的尝试:

  Map m; //contains a map with structure <i,j,List> where i and j are the coordinates in the sudoku table, and List is the initial Domain of that spot on the table;  

  public boolean arc-reduce(Node x, Node y){ 
  ArrayList l1 = m.get(x.i,x.j);
  ArrayList l2 = m.get(y.i,y.j);

  char one,two;
  boolean found=false, change=false;

  for(int a=0;a<l1.size();a++){
     one = l1.get(a);
     found = false;            

     for(int b=0;b<l2.size();b++){
     two = l2.get(b);

         if(one==two && x.i==y.i) //same char same line
             found=true;
         if(one==two && x.j==y.j) //same char same column
             found=true;

     }
     if(found==false){
     l1.remove(i);
     change=true;
     }

  }
  return change;
  }

在它的当前状态下,我应用此修改后的域名是不正确的。我的实施有缺陷吗?我会很感激一些提示让我朝着正确的方向前进,因为这个问题让我很麻烦。

1 个答案:

答案 0 :(得分:1)

R2约束是两个变量之间的二元约束。在Sudoku中,有3种不同的二元约束类型。对于Sudoku的给定节点(square)n:(1)n行中的每个节点都不能与n具有相同的值。 (2)n列中的每个节点都不能与n具有相同的值。 (3)与n相同的正方形中的每个节点不得与n具有相同的值。

您需要将这些约束表示为R2约束。您不需要像伪代码那样完全这样做,这只是算法的大纲。数独的想法是,当您进行分配或更改节点的域时,必须强制与其具有关系的节点的域保持一致(减少同一行,列和方块中的域的域) 。希望对你有帮助。

相关问题