4

そこで最近、英国の GCHQ が投稿した次のパズルを見ました。

25x25 のノノグラムを解く必要があります。

ノノグラムは、隠された絵を明らかにするために、グリッドの横の数字に応じてグリッド内のセルを色付けするか空白のままにする必要がある絵論理パズルです。このタイプのパズルでは、数字は離散トモグラフィーの形式であり、特定の行または列に塗りつぶされた正方形の途切れのない行がいくつあるかを測定します。たとえば、「4 8 3」の手がかりは、4 つ、8 つ、3 つの塗りつぶされた正方形のセットがこの順序であり、連続するグループの間に少なくとも 1 つの空白の正方形があることを意味します。

当然のことながら、私はそれを解決するプログラムを作成しようとする傾向がありました。行0から始まる再帰的なバックトラッキングアルゴリズムを考えていました.行の手がかりからの情報を与えられたその行の可能な配置ごとに、次の行の可能な組み合わせを配置し、列が与えられた有効な配置であるかどうかを検証します.手がかり。そうである場合は、すべての行が有効な構成に配置されるか、すべての可能な行の組み合わせが使い尽くされるまで、バックトラックを続けます。

いくつかの 5x5 パズルでテストしましたが、完璧に動作します。問題は、25x25 GCHQ パズルの計算に時間がかかりすぎることです。このアルゴリズムをより効率的にする方法が必要です - 上にリンクされたパズルを解くのに十分です. 何か案は?

これは、各行の行の可能性のセットとソルバーのコードを生成するための私のコードです (注* いくつかの非標準ライブラリを使用していますが、これは要点を損なうものではありません):

// The Vector<int> input is a list of the row clues eg. for row 1, input = {7,3,1,1,7}. The 
// int currentElemIndex keeps track of what block of the input clue we are dealing with i.e 
// it starts at input[0] which is the 7 sized block and for all possible places it can be 
// placed, places the next block from the clue recursively.

// The Vector<bool> rowState is the state of the row at the current time. True indicates a 
// colored in square, false indicates empty.

// The Set< Vector<bool> >& result is just the set that stores all the possible valid row 
// configurations. 

// The int startIndex and endIndex are the bounds on the start point and end point between 
// which the function will try to place the current block. The endIndex is calculated by 
// subtracting the width of the board from the sum of the remaining block sizes + number 
// of blocks remaining. Ie. if for row 1 with the input {7,3,1,1,7} we were placing the 
// first block, the endIndex would be (3+1+1+7)+4=16 because if the first block was placed
// further than this, it would be impossible for the other blocks to fit. 

// BOARD_WIDTH = 25;

// The containsPresets funtion makes sure that the row configuration is only added to the 
// result set if it contains the preset values of the puzzle (the given squares
// at the start of the puzzle).



void Nonogram::rowPossibilitiesHelper(int currentElemIndex, Vector<bool>& rowState, 
                                         Vector<int>& input, Set< Vector<bool> >& result, 
                                            int startIndex, int rowIndex) {
    if(currentElemIndex == input.size()) {         
        if(containsPresets(rowState, rowIndex)) {
            result += rowState;
        }
    } else {
        int endIndex = BOARD_WIDTH - rowSum(currentElemIndex+1, input);
        int blockSize = input[currentElemIndex];
        for(int i=startIndex; i<=endIndex-blockSize; i++) {
            for(int j=0; j<blockSize; j++) {
                rowState[i+j] = true;                                                                       // set block
            }
            rowPossibilitiesHelper(currentElemIndex+1, rowState, input, result, i+blockSize+1, rowIndex);   // explore
            for(int j=0; j<blockSize; j++) {
                rowState[i+j] = false;                                                                      // unchoose
            }
        }
    }
}


// The function is initally passed in 0 for the rowIndex. It gets a set of all possible 
// valid arrangements of the board and for each one of them, sets the board row at rowIndex
// to the current rowConfig. Is then checks if the current configuration so far is valid in 
// regards to the column clues. If it is, it solves the next row, if not, it unmarks the 
// current configuration from the board row at rowIndex.

void Nonogram::solveHelper(int rowIndex) {
    if(rowIndex == BOARD_HEIGHT) {
        printBoard();
    } else {
        for(Vector<bool> rowConfig : rowPossisbilities(rowIndex)) {
            setBoardRow(rowConfig, rowIndex);
            if(isValidConfig(rowIndex)) {                           // set row
                solveHelper(rowIndex+1);                            // explore
            }
            unsetBoardRow(rowIndex);                                // unset row
        }
    }
}
4

1 に答える 1

3

私はJavaで解決策を作成しました.あなたの例のパズル(25x25)は約50ms.

完全なコードと入力例: Github


前提条件

  • Java の概念 (サンプルの理解)
  • ビット単位の操作: 私はそれらに大きく依存しているので、あまり詳しくない場合は読んでください。
  • グラフ走査アルゴリズム: DFS

与えられた:

R, C // number of rows, columns
int[][] rows; // for each row the block size from left to right (ex: rows[2][0] = first blocksize of 3 row)
int[][] cols; // for each column the block size from top to bottom
long[] grid; // bitwise representation of the board with the initially given painted blocks

行ごとにすべての順列を事前に計算します。

順列もビット単位の表現で格納されます。最初の列などを埋める場合、最初のビットがtrueに設定されます。これは、時間とスペースの両方で効率的です。計算のために、最初に追加できる余分なスペースの数を数えます。

これはnumber_of_columns - sum_of_blocksize - (number_of_blocks-1)

余分なスペースを配置するすべての可能な順列に対する DFS。calcPerms最初に指定された塗装済みブロックと一致する場合は、可能な順列のリストにそれらを確認して追加します。

rowPerms = new long[R][];
for(int r=0;r<R;r++){
    LinkedList<Long> res = new LinkedList<Long>();
    int spaces = C - (rows[r].length-1);
    for(int i=0;i<rows[r].length;i++){
        spaces -= rows[r][i];
    }
    calcPerms(r, 0, spaces, 0, 0,res);
    rowPerms[r] = new long[res.size()];
    while(!res.isEmpty()){
        rowPerms[r][res.size()-1]=res.pollLast();
    }
}
...

// row, current block in row, extra spaces left to add, current permutation, current number of bits to shift
static void calcPerms(int r, int cur, int spaces, long perm, int shift, LinkedList<Long> res){
    if(cur == rows[r].length){
        if((grid[r]&perm)==grid[r]){
            res.add(perm);                
        }
        return;
    }
    while(spaces>=0){
        calcPerms(r, cur+1, spaces, perm|(bits(rows[r][cur])<<shift), shift+rows[r][cur]+1,res);
        shift++;
        spaces--;
    }
}
static long bits(int b){
    return (1L<<b)-1; // 1 => 1, 2 => 11, 3 => 111, ...
}

行ごとに検証を実装する

  • 行の検証:

[些細な こと:] 事前に計算された順列を使用するので、行ごとに追加の検証は必要ありません。

  • 列の検証:

ここでは、行と列ごとに現在のブロックサイズのインデックスとcolIxそのサイズの位置を保持していますcolVal

これは、前の行の値とインデックスによって計算されます。

  • 列が現在の行に描画されている場合、値は 1 増加します。
  • 列が前の行に描画され、現在の行にない場合、値は 0 にリセットされ、インデックスは 1 増加します。

サンプル:

static void updateCols(int row){
    long ixc = 1L;
    for(int c=0;c<C;c++,ixc<<=1){
        // copy from previous
        colVal[row][c]=row==0 ? 0 : colVal[row-1][c];
        colIx[row][c]=row==0 ? 0 : colIx[row-1][c];
        if((grid[row]&ixc)==0){
            if(row > 0 && colVal[row-1][c] > 0){ 
                // bit not set and col is not empty at previous row => close blocksize
                colVal[row][c]=0;
                colIx[row][c]++;
            }
        }else{
            colVal[row][c]++; // increase value for set bit
        }
    }
}

これらのインデックス/値を使用して、次の行でどのビットが false/true であると予想されるかを判断できます。

検証に使用されるデータ構造:

static long[] mask; // per row bitmask, bit is set to true if the bit has to be validated by the val bitmask
static long[] val; // per row bitmask with bit set to false/true for as expected for the current row

前の行のビットが設定されている場合、現在の行のビットが true に設定されるのは、現在のサイズが現在のインデックスの予想サイズよりもまだ小さい場合に限られます。それ以外の場合は、現在の行で切り取るために 0 にする必要があります。

または、最後のブロックサイズがすでに列に使用されている場合、新しいブロックを開始できません。したがって、ビットは 0 でなければなりません。

static void rowMask(int row){
    mask[row]=val[row]=0;
    if(row==0){
        return;
    }
    long ixc=1L;
    for(int c=0;c<C;c++,ixc<<=1){
        if(colVal[row-1][c] > 0){
            // when column at previous row is set, we know for sure what has to be the next bit according to the current size and the expected size
            mask[row] |= ixc; 
            if(cols[c][colIx[row-1][c]] > colVal[row-1][c]){
                val[row] |= ixc; // must set
            }
        }else if(colVal[row-1][c] == 0 && colIx[row-1][c]==cols[c].length){
            // can not add anymore since out of indices
            mask[row] |= ixc;
        }
    }
}

すべての行を DFS し、まだ有効かどうかを確認します

これにより、実際の dfs 部分が自分のものと同じくらい簡単になります。行マスクが現在の構成に適合する場合、列のインデックス/値を更新し、次の行にトラバースして、最終的に行 R にたどり着くことができます。

static boolean dfs(int row){
    if(row==R){
        return true;
    }
    rowMask(row); // calculate mask to stay valid in the next row
    for(int i=0;i<rowPerms[row].length;i++){
        if((rowPerms[row][i]&mask[row])!=val[row]){
            continue;
        }
        grid[row] = rowPerms[row][i];
        updateCols(row);
        if(dfs(row+1)){
            return true;
        }
    }
    return false;
}
于 2015-12-27T22:02:47.513 に答える