瑣碎BFS/DFS

簡單部分和

給定n個數字,能否取出部分數字的和等於k。

DFS適合於解決“是否存在解”的問題。複雜度隨數據量呈指數級上升,只適合於小數據量。

DFS(i, sum)表示處理完前i-1個數以後的和爲sum,正要對第i個數處理。對第i個數處理時,要麼將s[i]加到sum裏,要麼跳過這個數,然後繼續搜索。
剪枝:當處理到第i個數時已經溢出k,則直接返回false。

#include <iostream>
using namespace std;
const int maxn = 100;
int n, k, s[maxn];

bool DFS(int i, int sum) //處理完前i-1個數後和爲sum
{
    if (i == n || sum > k) return false; //搜索到底或溢出
    if (sum == k) return true;
    if (DFS(i+1, sum+s[i]) || DFS(i+1, sum)) //繼續搜索
        return true;
    return false;
}


int main()
{
    cin >> n >> k;
    for (int i = 0; i<n; ++i)
        cin >> s[i];
    if (DFS(0,0))
        cout << "YES!" << endl;
    else cout << "NO!" << endl;
    return 0;
}

迷宮

搜索入門(BFS)迷宮的最短路徑 - stack_queue的博客 - 博客頻道 - CSDN.NET
http://blog.csdn.net/stack_queue/article/details/53394352

#include <iostream>
#include <queue>
using namespace std;
const int maxn = 105, INF = 1<<27;

int mark[maxn][maxn]; //標記到達mark[i,j]的最少步數
char maze[maxn][maxn];
int n, m;
//上右下左四個方向
const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};

typedef pair<int, int> P; //first代表行,second代表列
int BFS(int row, int col)
{
    mark[row][col] = 0;
    queue<P> q;
    q.push(P(row, col)); //加入起點
    while (!q.empty())
    {
        P out = q.front(); q.pop();
        int r = out.first, c = out.second;
        if (maze[r][c] == 'G') //找到終點,輸出長度
            return mark[r][c];
        for (int i = 0; i < 4; ++i) //廣度優先擴展節點
        {
            int x = r + dx[i], y = c + dy[i];
            if (x < 0 || y < 0 || x >= n || y >= m)
                continue;
            if (mark[x][y] == 0 && maze[x][y] != '#') //(x,y)沒有訪問過且能通過(包括G和'.')
            {
                mark[x][y] = mark[r][c] + 1;
                q.push(P(x,y));
            }
        }
    }
    return -1;
}

int main()
{
    fill(mark[0], mark[0]+maxn, 0); //初始化爲0,可以用來表示是否(i,j)訪問過
    cin >> n >> m;
    for (int i = 0; i<n; ++i)
        cin >> maze[i];
    int ans = -1;
    for (int i = 0; i<n; ++i)
        for (int j = 0; j<m; ++j)
            if(maze[i][j] == 'S')
            {
                ans = BFS(i, j);
                cout << "Maze-Solution Length: " << ans << endl;
                return 0;
            }
    cout << ans << endl;
    return 0;
}
發佈了116 篇原創文章 · 獲贊 27 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章