【蓝桥杯每日一题】4.10搜索练习

蓝桥杯就要来咯,加油!

T1:

题目来源:
3472. 八皇后 - AcWing题库

  • 简单的八皇后问题,唯一注意点在于怎么存放数值
#include<bits/stdc++.h>
using namespace std;

int a[8][8];
int n,b;
char s[8];  //字符串形式好存放,不用在*10+了
int res[100]; //由于存放解法数据
bool col[20],dui[20],fandui[20];
int id=0;

void dfs(int m)
{
	if(m==8){
		res[++id]=atoi(s);
		return ;
	}
	for(int i=0;i<8;i++)
	{
		if(!col[i]&&!dui[m+i]&&!fandui[8-m+i])
		{
			s[m]=i+1+'0'; //第u个皇后所在的位置
			col[i]=dui[m+i]=fandui[8-m+i]=true; //标记列、对角线、反对角线
			dfs(m+1);
			col[i]=dui[m+i]=fandui[8-m+i]=false;
		}
	}
}
int main(){
	
	dfs(0);
	scanf("%d",&n);
	
	while(n--)
	{
		scanf("%d",&b);
		printf("%d\n",res[b]);
	}
	
	return 0;
}

T2:

3699. 树的高度 - AcWing题库

DFS:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;

int n,m;
int res;
vector<int> a[N]; //其实算是一个二维数组,每行存放相连的节点ID,相比更加省空间
bool vis[N];

void dfs(int depth,int k)
{
	res=max(res,depth);
	
	for(auto i: a[k])
	{
		if(!vis[i])
		{
			vis[i]=1;dfs(depth+1,i);
		}
	}
}

int main()
{
	scanf("%d%d",&n,&m);
	
	while(n--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		a[x].push_back(y);	 //无向边
		a[y].push_back(x);
	}
	vis[m]=1;
	dfs(0,m);
	
	printf("%d",res);	
	return 0;
}

BFS:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int m, n;
int dep[N];
vector<int> a[N];
int res = 0;

void bfs() 
{
    queue<int> q;
    q.push(m);
    dep[m] = 0;
    while (!q.empty()) 
	{
        int u = q.front();
        q.pop();
        
        for (int i=0;i<a[u].size();i++) 
		{
            int v = a[u][i];
            
            //特判防止根节点被计算
            if(v==m)continue;
            if (!dep[v])
			{
				dep[v] = dep[u] + 1;
				res=max(res,dep[v]);
				q.push(v);
			}
        }
    }
}


int main() 
{
    scanf("%d%d",&n,&m);

	while(n--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		a[x].push_back(y);	 //无向边
		a[y].push_back(x);
	}
	
    bfs();
   	printf("%d",res);
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值