深度优先搜索DFS3(c++)

题目

八皇后问题

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

int n;
int a[10][10];
int cnt;

void dfs(int,int);
void print();
bool panduan(int,int);

int main()
{
	
	n = 8;
	for(int i = 1;i<=n;i++)
	{
		a[1][i] = 1;
		dfs(1,i);
		a[1][i] = 0;
	}
	
	
	return 0;
}
void dfs(int x,int y)
{
	if(x==8)
	{
		print();
		return;
	}
	int tx = x+1;
	int ty = 1;
	for(ty = 1;ty<=n;ty++)
	{
		if(panduan(tx,ty)==true)
		{
			a[tx][ty] = 1;
			dfs(tx,ty);
			a[tx][ty] = 0;
		}
	}
	return;
}
void print()
{
	cnt++;
	cout<<"No."<<cnt<<endl;
	for(int i = 1;i<=n;i++)
	{
		for(int j = 1;j<=n;j++)
		{
			cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
}
bool panduan(int x,int y)
{
	for(int i = 1;i<=n;i++)
	{
		if(a[i][y]==1&&i!=x) return false;
	}
	int i = x-1,j = y-1;
	while(i>=1&&j>=1)
	{
		if(a[i][j]==1) return false;
		i--;
		j--;
	}
	i = x+1,j = y+1;
	while(i<=n&&j<=n)
	{
		if(a[i][j]==1) return false;
		i++;
		j++;
	}
	i = x+1,j = y-1;
	while(i<=n&&j>=1)
	{
		if(a[i][j]==1) return false;
		i++;
		j--;
	}
	i = x-1,j = y+1;
	while(i>=1&&j<=n)
	{
		if(a[i][j]==1) return false;
		i--;
		j++;
	}
	
	return true;
}

棋盘问题

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
struct node
{
	int x,y;
	node(){};
	node(int aaaaa,int bbbbb)
	{
		x = aaaaa;
		y = bbbbb;
	}
};

int n,k;
char a[10][10];
node b[1010];
int lb;
int cnt;


void dfs(int,int);
bool xuan(int,int);

int main()
{
	
	cin>>n>>k;
	while(n!=-1&&k!=-1)
	{
		for(int i = 1;i<=n;i++)
		{
			for(int j = 1;j<=n;j++)
			{
				cin>>a[i][j];
				if(a[i][j]=='#') b[++lb] = {i,j};
			}
		}
		cnt = 0;
		
		dfs(0,0);
		cout<<cnt<<endl;
		cin>>n>>k;
	}
	
	
	
	
	return 0;
}
void dfs(int v,int vb)
{
	
	if(v==k)
	{
		cnt++;
		return;
	}
	if(vb>=lb) return;
	
	vb++;
	dfs(v,vb);
	if(xuan(b[vb].x,b[vb].y)==true)
	{
		a[b[vb].x][b[vb].y] = '@';
		dfs(v+1,vb);
		a[b[vb].x][b[vb].y] = '#';
	}
	
	
	return;
}
bool xuan(int xx,int yy)
{
	
	for(int i = 1;i<=n;i++)
	{
		if(a[i][yy]=='@'||a[xx][i]=='@') return false;
	}
	
	return true;
}
相关推荐
我不会插花弄玉1 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴3 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David3 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus3 小时前
C++ explicit 关键字工程实践
开发语言·c++
Pniubi6 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK6 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司7 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
一拳一个呆瓜8 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso8 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化9 小时前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3