回溯法--騎士遊歷問題

基本思想就是宏觀看問題,微觀交給計算機自己運行。先上代碼

#include <iostream>
using namespace std;
int chess[8][8]={};
int counts=0;
bool ifout(int x,int y){//判斷是否出界 
	if(x>=0&&x<=7&&y>=0&&y<=7){
		return false;
	}else{
		return true;
	}
}

bool ifVisited(int x,int y){
	if(chess[x][y]!=0){
		return true;
	}else{
		return false;
	}
}


void dfs(int x,int y){
	if(counts==64)
		return ;
	if(!ifVisited(x,y)&&!ifout(x,y)){
		counts++;
		chess[x][y]=counts;
		dfs(x+2,y+1);
		dfs(x+1,y+2);
		dfs(x-1,y+2);
		dfs(x-2,y+1);
		dfs(x-2,y-1);
		dfs(x-1,y-2);
		dfs(x+1,y-2);
		dfs(x+2,y-1);
		return ;
	}else{
		return ;
	}
}

int main(){
	int x,y;
	cout<<"輸入起始位置x和y:";
	while(1){
		cin>>x>>y;
		if(x>7||y>7||x<0||y<0){
			cout<<"輸入座標有誤,請重新輸入:";
		}else{
			break;
		}
	} 
	dfs(x,y);
	for(int i=0;i<8;i++){
		for(int j=0;j<8;j++){
			cout<<chess[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
} 

這算是一道很簡單的回溯法的題目了,代碼應該很好懂!

根據這位博主的算法思想寫的:https://blog.csdn.net/qq_41767945/article/details/92796520#comments

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章