數獨遊戲的AI解法

2021-04-09 02:54:26 字數 1645 閱讀 1029

因為解的過程沒有全域性狀態這種概念,所以不方便使用著名的h>d模板來解。其實因為格仔的數量很少,只要做簡章的優化就完全不存在問題。即使用窮舉法,也能很快算出答案。(某人:不要小看窮舉法!!!>_<++)

下次準備考慮生成遊戲的演算法,難度應該較高。

console工程的**

// sudoku.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "conio.h"

/* 為了**好看^^ */

#define success  1

#define failed  0

/* 地圖型別9*9的char,每個char從0-9,0表示待填 */

typedef char maptype[9][9];

/*  行資料,同時用作「可能性」資料。如linetype a; 當a[0]為真時表示

當前位置可填1,a[1]為真時表示可填2,以此類推 */

typedef char linetype[9];

/* 測試用地**本,摘自http://www.game616.com/ */

const char *_map1 = ;

/* 從地**本讀取生成地圖。地**本是連續的81個asc數字字串 */

void parse_map(maptype dest, const char* src)

}/* 列印地圖 */

void dump_map(maptype dest)

printf("/n");

}printf("/n");

}int fill_line(maptype dest, int line, maptype result);

/* 填下乙個格仔。本行的可能性已在呼叫前算好,要考慮的是列的可能性和九宮格的可能性 */

/* nums_possible : array (0-8) means possible of number (1-9) */

int fill_pos(maptype dest, linetype nums_possible, int line, int pos, maptype result)

if ( vetical_failed ) continue;

/* 檢查九宮格是否重複 */

int nine_failed = 0;

int m = pos / 3;

int n = line / 3;

m *= 3;

n *= 3;

for ( int y = n; y < n + 3; y++ )

}if ( nine_failed ) break;

}if ( nine_failed ) continue;

/* all ok, try next position */

dest[pos][line] = i + 1;

nums_possible[i] = 0;

if ( fill_pos(dest, nums_possible, line, pos + 1, result) )

nums_possible[i] = 1;

dest[pos][line] = 0;

}return failed;

}int _tmain(int argc, _tchar* argv)

數獨遊戲的深度優先遍歷解法

數獨簡介 數獨 是一種邏輯性的數字填充遊戲,玩家須以數字填進每一格,而每行 每列和每個宮 即3x3的大格 有齊1至9所有數字。遊戲設計者會提供一部份的數字,使謎題只有乙個答案。乙個已解答的數獨其實是一種多了宮的限制的拉丁方陣,因為同乙個數字不可能在同一行 列或宮中出現多於一次。深度優先遍歷演算法 學...

數獨遊戲的解法到App的實現

在leetcode上偶然刷到乙個解數獨的題目 編寫乙個程式,通過已填充的空格來解決數獨問題。乙個數獨的解法需遵循如下規則 note 這個題目很是有趣,解決了數獨算不出來的難題。首先想到的是暴力列舉了,也就是對每個空格進行列舉,回溯法。public void solvesudoku char boar...

數獨解法 C 實現

include using namespace std 構造完成標誌 bool sign false 建立數獨矩陣 int num 9 9 函式宣告 void input void output bool check int n,int key int dfs int n 主函式 int main ...