第八届蓝桥杯C++B组 方格分割(dfs)

1.png2.png3.png

#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
int chess[7][7];
int total;
void dfs(int row,int col){
	if(row==0||col==6||row==6||col==0){//走到边了
		total++;//总数+1
		return;
	}
	for(int i=0;i<4;i++){//上下左右四个方向搜索
		int xx=row+dx[i];
		int yy=col+dy[i];
		if(xx>=0&&yy>=0&&xx<=6&&yy<=6){//判断是否越界
			if(chess[xx][yy]==0){//没走过
				chess[xx][yy]=1;//标记
				chess[6-xx][6-yy]=1;//中心对称点也标记
				dfs(xx,yy);//继续搜索
				chess[xx][yy]=0;//恢复
				chess[6-xx][6-yy]=0;//恢复
			}
		}
	}
}
int main(){
	chess[3][3]=1;
	dfs(3,3);//从中心点开始搜索
	cout<<total/4;//为什么除以4?关于中心对称,旋转四个方向的四种其实是一种
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cong427/article/details/88756601
今日推荐