深度优先探索与广度优先探索
遍历所有状态最好用dfs,求最短路用bfs,(无权值,都是一);
要注意满足状态与越界状态。(必要时设标志位)
dfs
bool judge(){ int k, p, q; for(int i = 0; i < n; i++){ if(b[i] == true) k++; } for(int i = 0; i < n; i++){ if(b[i] == true) { p = a[i]; break; } } for(int i = n - 1; i >= 0; i--){ if(b[i] == true) { q = a[i]; break; } } return k >= 2 && q - p >= x; } void dfs(int i, int sum){ if(i == n){ if(judge() && sum >= l && sum <= r){ num++; } return; } b[i] = false; dfs(i + 1, sum); b[i] = true; dfs(i + 1, sum + a[i]); }
bool judge(){ int k = 0, p = 0, q = 0; for(int i = 0; i < n; i++){ if(b[i] == true) k++; } for(int i = 0; i < n; i++){ if(b[i] == true) { p = a[i]; break; } } for(int i = n - 1; i >= 0; i--){ if(b[i] == true) { q = a[i]; break; } } return k >= 2 && q - p >= x; } void dfs(int i, int sum, int minn, int maxx, int ppp){ if(i == n){ if(maxx - minn >= x && ppp >= 2 && sum >= l && sum <= r){ num++; } return; } b[i] = false; dfs(i + 1, sum, minn, maxx, ppp); b[i] = true; dfs(i + 1, sum + a[i], min(minn, a[i]), max(maxx, a[i]), ++ppp); }
这种可以统计数量
不统计数量的,因为有一个成立就全部返回了。
bool dfs(int i, int sum){ if(i == n){ if(judge() && sum >= l && sum <= r){ num++; return true; } return false; } b[i] = false; if(dfs(i + 1, sum)) { return true; } b[i] = true; if(dfs(i + 1, sum + a[i])){ return true; } return false; }
这个是八皇后问题,记一个标志位。
#include<cstdio> #include<iostream> #include<cstring> using namespace std; const int N = 8; int cnt; int board[15][15]; bool check(int x, int y) { for(int i = 0; i < x; i++) { if(board[i][y]) return false; } for(int i = 0; i < x; i++) { if(y - x + i < 0) continue; if(board[i][y - x + i]) return false; } for(int i = 0; i < x; i++) { if(y + x - i >= 8) continue; if(board[i][y + x - i]) return false; } return true; } void dfs(int x, int y) { if(x == 7) { cnt++; printf("No. %d\n", cnt); for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { printf("%d ", board[i][j]); } printf("\n"); } return; } for(int i = 7; i >= 0; i--) { board[x + 1][i] = 1; if(check(x + 1, i)) dfs(x + 1, i); board[x + 1][i] = 0; } } int main() { cnt = 0; memset(board, 0, sizeof(board)); for(int i = 0; i < 8; i++) { board[0][i] = 1; dfs(0, i); board[0][i] = 0; } }
下面是bfs;
const int INF = 1e8; typedef pair<int, int> P; char maze[MAX][MAX]; int N, M; int sx, sy; int gx, gy; int d[MAX][MAX]; int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; int dfs(){ queue<P> que; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ d[i][j] = INF; que.push(P(sx, sy)); d[sx][sy] = 0; while(que.size()){ P p = que.front(); que.pop(); if(p.first == gx && p.second == gy) break; for(int i = 0; i < 4; i++){ int nx = p.first + dx[i], ny = p.second + dy[i]; if(nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx][ny] != '#' && d[nx][ny] == INF){ que.push(P(nx, ny)); d[nx][ny] = d[p.first][p.second] + 1; } } } return d[gx][gy]; } void solve(){ int res = bfs(); } }
习题:https://cn.vjudge.net/contest/260332#problem/B
https://vjudge.net/contest/268095#problem/F
https://vjudge.net/contest/256610#problem/P