返回题解分享
讨论 / 题解分享/ 帖子详情

数字接龙(编程题) - 题解

#include <iostream>
#include <vector>
#include <set>
#include <string>

using namespace std;

using ll = long long;

// [y][x]
constexpr int fx[8][2] = {
	{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, 
	{1, 0}, {1, -1}, {0, -1}, {-1, -1}
};

int n = 0, k = 0;
vector<vector<int>> tizu;
vector<vector<int>> vis;
set<string> res;
string now;

int sb[10][10][10][10];

void dfs(int i, int j, int next) {
	if (i == n - 1 && j == n - 1) {
		if ((int)now.size() == n * n - 1) {
//			res.insert(now);
			cout << now << '\n';
			exit(0);
		}
		return;
	}
	next = (next + 1) % k;
	
	for (int d = 0; d < 8; ++d) {
		char c = '0' + d;
		int y = i + fx[d][0], x = j + fx[d][1];
		if (y < 0 || y >= n || x < 0 || x >= n || vis[y][x] || tizu[y][x] != next) {
			continue;
		}
		// [i][j] -> [y][x] 
		if (c == '1' && (sb[y+1][x][y][x-1] || sb[y][x-1][y+1][x]))
			continue;
		if (c == '3' && (sb[y-1][x][y][x-1] || sb[y][x-1][y-1][x]))
			continue;
		if (c == '5' && (sb[y-1][x][y][x+1] || sb[y][x+1][y-1][x]))
			continue;
		if (c == '7' && (sb[y+1][x][y][x+1] || sb[y][x+1][y+1][x]))
			continue;
		vis[y][x] = 1;
		sb[i][j][y][x] = 1;
		now += c;
		dfs(y, x, next);
		now.pop_back();
		sb[i][j][y][x] = 0;
		vis[y][x] = 0;
	}
}

int main() {
	cin >> n >> k;
	tizu = vector<vector<int>>(n, vector<int>(n));
	vis = vector<vector<int>>(n, vector<int>(n));
	
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j) 
			cin >> tizu[i][j];
	
	vis[0][0] = 1;
	if (tizu[0][0] == 0)
		dfs(0, 0, 0);
	cout << "-1\n";
	return 0;
}
0 回复 0 转发 1 喜欢 4 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!