数据结构与算法 / 回溯算法(八皇后、0 - 1 背包)
生活随笔
收集整理的這篇文章主要介紹了
数据结构与算法 / 回溯算法(八皇后、0 - 1 背包)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
回溯算法,顧名思義,就是在沒有得到最優解的前提下,不斷的返回至前面的岔路口位置,重新選擇,直至遍歷了所有的情況或者得到的預期最優解的情況下再結束。
與貪心算法不同的是,回溯算法理論上是可以得到最優解,而貪心算法則盡可能在快的情況下得到較理想的結果。
一、八皇后
下面的栗子就是八皇后問題,是一個典型的回溯算法應用栗子。其實本質上就是遍歷所有的可能性,最后滿足條件者打印出來。?
#include <iostream>unsigned int g_count = 0;bool isOK(unsigned char *p_result, const unsigned char &row, const unsigned char &column); void PrintResult(unsigned char *p_result); void Calc8Queens(unsigned char *p_result, const unsigned char &row);int main() {unsigned char result[8] = {5, 5, 5, 5, 5, 5, 5, 5};Calc8Queens(result, 0);std::cout << "共有 " << g_count << " 個結果" << std::endl;return 0; }bool isOK(unsigned char *p_result, const unsigned char &row, const unsigned char &column) {if (p_result == nullptr)return false;unsigned char leftup = column - 1;unsigned char rightup = column + 1;for (int i = row - 1; i >= 0; --i){if (p_result[i] == column)return false;if (leftup >= 0){if (p_result[i] == leftup)return false;}if (rightup < 8){if (p_result[i] == rightup)return false;}leftup--;rightup++;}return true; }void PrintResult(unsigned char *p_result) {if (p_result == nullptr)return;for (unsigned char i = 0; i < 8; ++i){for (unsigned char k = 0; k < p_result[i]; ++k)std::cout << "-"<< " ";std::cout << "a"<< " ";for (unsigned char k = p_result[i] + 1; k < 8; ++k)std::cout << "-"<< " ";std::cout << std::endl;}std::cout << std::endl;std::cout << std::endl;return; }void Calc8Queens(unsigned char *p_result, const unsigned char &row) {if (p_result == nullptr)return;if (row >= 8){g_count++;PrintResult(p_result);return;}for (int column = 0; column < 8; ++column){if (isOK(p_result, row, column)){p_result[row] = column;Calc8Queens(p_result, row + 1);}}return; }結果太多了,就不寫出來了,共有 92 個可能性。?
二、0 - 1 背包
#include <iostream>unsigned int g_max = 0; void func(const int &index, const int &cw, const int *const pitems, const int &count, const int &maxW);int main() {int items[10] = {80, 20, 90, 9, 50, 6, 70, 8, 9, 10};func(0, 0, items, 10, 111);std::cout << "所能容納的最大的物件重量為 " << g_max << std::endl;return 0; }void func(const int &index, const int &cw, const int *const pitems, const int &count, const int &maxW) {if (cw == maxW || index >= count){if (cw > g_max)g_max = cw;return;}func(index + 1, cw, pitems, count, maxW);if (cw + pitems[index] <= maxW)func(index + 1, cw + pitems[index], pitems, count, maxW);return; }結果為 110 。
?
(SAW:Game Over!)
?
?
?
總結
以上是生活随笔為你收集整理的数据结构与算法 / 回溯算法(八皇后、0 - 1 背包)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OS / Linux / SIGKILL
- 下一篇: margin 和 padding 的使用