蓝桥杯真题-路径之谜

蓝桥杯真题-路径之谜_第1张图片

思路:用dfs遍历,同时记录北边和西边数字变化,走到终点与给定箭靶数字比较,一致就是正确的路径。解题过程中直接遍历,会有案例超时,所以得用剪枝。

#include
using namespace std;
#include
#include
#include
#include
int N;
vectornorth1(20, 0);
vectorwest1(20, 0);
vectorresult;
bool dfs(vector>map, vector>&flag,int x,int y, vectornorth, vector& west) {
	int turn[4][2] = { -1,0,1,0,0,-1,0,1 };
	flag[x][y] = true;
	west1[x]++;
	north1[y]++;
	result.push_back(map[x][y]);
	if (west1[x] > west[x] || north1[y] > north[y])return false;//剪枝,不然代码超时
	if (x==N-1&&y==N-1) {
		for (int j = 0;j < N;j++) {
			if (north1[j] != north[j] || west1[j] != west[j])
				return false;
		}
		return true;
	}
	for (int i = 0;i < 4;i++) {
		int nextx = x + turn[i][0];
		int nexty = y + turn[i][1];
		if (nextx < 0 || nextx >= N || nexty < 0 || nexty >= N)continue;
		if (!flag[nextx][nexty]) {
			if (!dfs(map, flag, nextx, nexty, north, west))
			{
				flag[nextx][nexty] = false;
				west1[nextx]--;
				north1[nexty]--;
				result.pop_back();
				
			}
			else return true;
			
		}
	}
	return false;
	
}
int main() {
	cin >> N;
	vector>flag(N, vector(N, false));
	vector>map(N, vector(N, 0));
	vectornorth(N,0);
	vectorwest(N, 0);
	for (int i = 0;i < N;i++) {
		cin >> north[i];
	}
	for (int i = 0;i < N;i++) {
		cin>>west[i];
	}
	int value = 0;
	for (int i = 0;i < N;i++) {
		for (int j = 0;j < N;j++) {
			map[i][j] = value;
			value++;
		}
	}
	dfs(map, flag, 0, 0,north,west);
	
	for (int i = 0;i < result.size();i++) {
		cout << result[i] << " ";
	}

}

你可能感兴趣的:(蓝桥杯,图论,算法,c++,dfs,路径之谜,剪枝)