Alpha-Beta搜尋很簡單
阿新 • • 發佈:2022-12-11
程式碼:
/* d=3 a=96 b=-69 BCDE d=2 a=69 b=-96 FGHI d=1 a=96 b=-69 MLKJ eval=7 -7(v) >= -69(b) ret 7(v) >= -96(b) ret -7(v) >= -69(b) ret 7 */ // https://www.xqbase.com/computer/search_intro2.htm // https://www.xqbase.com/computer/search_intro3.htm #include <stdio.h> #includeView Code<vector> struct { char* haizi; int v; } nodes[] = { { "BCDE" }, // A { "FGHI" }, // B { "" }, { "" }, { "" }, // CDE { "KJLM" }, // F 改這裡可以“排序” { "NO" }, // G { "" }, { "" }, // HI { "", 11 }, // J { "", 12 }, // K { "", 9 }, // L { "", 7 }, // M { "", 5 }, // N { "", 6 }, // O }; std::vector<int> pstack; // position stack char* gen_moves() { return nodes[pstack.back()].haizi; } void apply_move(char m) { pstack.push_back(m - 'A'); } void undo_move() { pstack.pop_back(); } int eval() { return nodes[pstack.back()].v; } #define I do { for (int i = 0; i < 4 - d; i++) putchar(' '); } while (0) intalpha_beta(int d, int a, int b) { if (d <= 0) { int v = eval(); I;printf("eval=%d\n", v); return v; } char* moves = gen_moves(); I;printf("d=%d a=%d b=%d %s\n", d, a, b, moves); for (char* p = moves; *p; p++) { apply_move(*p); int v = -alpha_beta(d - 1, -b, -a); undo_move(); if (v >= b) { I;printf("%d(v) >= %d(b) ret\n", v, b); return v; } if (v > a) { I;printf("%d(v) > %d(a)", v, a); a = v; } } I;printf("ret %d\n", a); return a; } int main() { pstack.push_back(0); printf("%d\n", -alpha_beta(3, 96, -69)); getchar(); return 0; }
這就對了?改下節點F的子節點的順序試試?
基本搜尋方法——簡介(三) 解釋為什麼排序這一步是很重要的。
其實本文的原標題是“Alpha-Beta搜尋很簡單…………嗎?”,聳人聽聞騙下點選。:-)
Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array.