学了一周的深搜和广搜,有点蒙,不过印象还是全的,怕学过就忘还是抽个时间来整理一下
首先呢,感觉相对简单点的BFS吧。
BFS(Breadth First Search)就是传说中的广度优先算法
大致上就是步步为营。
从开始点开始,先将开始点压入队列。
从队列中取出头一个元素,放到now中,并pop()掉它,以他为中心,访问四个方向的邻格,若符合条件,则压入队列。四个方向访问完成后,则重新从队列中取出头元素,直至队列为空,或找到符合条件的点。
类似下列题目
//A*算法,还不大清楚
#include<bits/stdc++.h>
using namespace std;
int maze[70][70]={0}; //导入矩阵
int vis[70][70]={0}; //标记该元素是否被访问过,若访问过则表示当前并不是最优解,应跳过
int m,n,ans=0;
int mov[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//对应节点向上、右、下、左四个方向。 //表示向四个方向移动
struct node{
int x,y,step;
};
void bfs(int x,int y){
node start;
start.x=x;start.y=y;
queue<node> q;
q.push(start);
vis[start.x][start.y]=1;
maze[start.x][start.y]=0;//
while(!q.empty()){
node now = q.front();
q.pop();
for(int i=0;i<4;i++){
int nx=now.x + mov[i][0];
int ny=now.y + mov[i][1];
// cout<<"x="<<now.x<<" y="<<now.y<<" maze="<<maze[x][y]<<endl;//
node next;//定义一个即将入队的向量
if(vis[nx][ny]==0 && maze[nx][ny]==1 && nx>=0 && nx<m && ny>=0 && ny<n )
{
vis[nx][ny]=1;
maze[nx][ny]=0;//
next.x=nx;
next.y=ny;
q.push(next);
}
}
}
}
int main(){
cin>>m>>n;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(maze[i][j]==1 && vis[i][j]==0){
bfs(i,j);ans++;
}
}
}
cout<<ans;
}
八数码问题
#include<iostream>
#include<map>
#include<queue>
#include<algorithm>
#define ll long long
using namespace std;
const ll dx[]={-1,0,0,1},dy[]={0,-1,1,0};
ll n;
int main()
{
cin>>n;
queue<ll> q;
q.push(n);
map<ll,ll> m;
m[n]=0;
while(!q.empty())
{
int u=q.front();
int c[3][3],f=0,g=0,n=u;q.pop();
if(u==123804765)break;
for(ll i=2;i>=0;i--)
for(ll j=2;j>=0;j--)
{
c[i][j]=n%10,n/=10;
if(!c[i][j])f=i,g=j;
}
for(ll i=0;i<4;i++)
{
ll nx=f+dx[i],ny=g+dy[i],ns=0;
if(nx<0||ny<0||nx>2||ny>2)continue;
swap(c[nx][ny],c[f][g]);
for(ll i=0;i<3;i++)
for(ll j=0;j<3;j++)ns=ns*10+c[i][j];
if(!m.count(ns))
{
m[ns]=m[u]+1;
q.push(ns);
}
swap(c[nx][ny],c[f][g]);
}
}
cout<<m[123804765]<<endl;
return 0;
}
DFS(Deepth First Search)就是传说中的深度优先算法
就是和BFS两个模式,先选一路,用递归一路走到黑,在搜寻其他分支。
核心代码 dfs(int now)先设定一个递归出口,在以dfs(now+1)进行递归寻找。
n皇后问题
#include<bits/stdc++.h>
using namespace std;
int n;
int a[12]={0};
int r,c;
int flag1=0,flag2=0;
bool check(int c,int r){
for(int i=0;i<r;i++){
if(a[i]!=0 || (abs(a[i]-c)==abs(i-r))){
return false;
}
}
return true;
}
void dfs(int r){
if(r==(n)){
for(int i=0;i<n;i++){
printf("%5d",a[i]);
}
cout<<endl;
return;
}
for(int c=0;c<n;c++){
if(check){
a[r]=c;
dfs(r+1);
}
}
}
int main(){
cin>>n;
dfs(0);
}