• 算法——回溯法(1)


    N皇后问题

    #include<iostream>
    using namespace std;
    #define n 4
    int count;
    int x[n+1];//代表坐标(q, [q])
    
    int place(int q) { //判断能否把Q放在第q行的某列
    	int i;
    	for(i = 1; i < q; i++) {
    		if(abs(q-i)==abs(x[q]-x[i])||x[q]==x[i]) { //判断是否同列或者同斜线
    			return 0;
    		}
    	}
    	return 1;
    }
    
    void BackTrack(int q) {
    	if(q > n) {
    		for(int i = 1; i <= n; i++) {
    			cout<<x[i]<<" ";
    		}
    		cout<<endl;
    		count++;
    	}
    
    	for (int j=1; j<=n; j++) {//从第1列循环放到第n列
    		x[q] = j;  //把q放在第j列
    		if(place(q) == 1) { //判断能不能把q放在第j列
    			BackTrack(q+1);
    		}
    	}
    
    }
    
    int main() {
    	
    	BackTrack(1);
    	cout<<count<<endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    图涂色问题

    #include<iostream>
    using namespace std;
    int c[100][100]; //邻接矩阵
    int color[100];  //记录每个顶点的颜色
    int count,m,n; //count记录方案数 n个顶点 m种颜色
    int Check(int k) {  //检查第i个顶点的颜色是否满足条件
    	for(int i = 1; i <= k; i++) {
    		if(c[k][i]==1&&color[i]==color[k]) //k与i之间相连并且i顶点的颜色与k顶点的颜色相同
    			return 0;
    	}
    	return 1;
    }
    
    void graphColor(int step) {
    	if(step==n+1) { //表示前面所有的顶点颜色都已经填完
    		for(int i=1; i<=n; i++)
    			cout<<color[i];
    		count++;
    		cout<<endl;
    		return ;
    	} else {
    		for(int i=1; i<=m; i++) {
    			color[step]=i;   //首先将这个顶点颜色换为i
    			if(Check(step)==1) { //检查是否符合条件
    				graphColor(step+1); //符合条件则走下一步
    
    			}
    			color[step]=0;  //回溯 置为0
    		}
    	}
    }
    
    int main(void) {
    	cin>>n>>m;//n个顶点 m种颜色
    	for(int i = 1; i <= n; i++)
    		for(int j = 1; j <= n; j++) {
    			cin>>c[i][j];
    		}
    
    	graphColor(1);
    	cout<<count;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
  • 相关阅读:
    JS hook 3种方法
    AST2500常用操作命令
    培养核心人才,落实IPD体系
    【面试经典150 | 链表】合并两个有序链表
    【webpack】wabpack5 知识梳理
    java计算机毕业设计翔隆生鲜超市进货管理系统源程序+mysql+系统+lw文档+远程调试
    docker-compose的部署
    RK3568 启动失败
    Dev C++ 注释中文乱码问题及解决方法
    跳动爱心代码-李峋同款爱心代码1(完整代码)
  • 原文地址:https://blog.csdn.net/m0_55825393/article/details/124857129