谜一般的格式换行,为啥格式错报WA额。
这题也是用回溯法解决,只是判断情况稍微复杂些。
本质都是相同的,每次有两种决策,一行一行来处理。
当进行到某一行时,上一行还存在未vis的位置则回溯。
这题也是用回溯法解决,只是判断情况稍微复杂些。
本质都是相同的,每次有两种决策,一行一行来处理。
当进行到某一行时,上一行还存在未vis的位置则回溯。
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cctype>
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define LL long long
#define mod 1000000007
#define INF 1000000007
#define eps 1e-5
#define PI 3.1415926535898
using namespace std;
//-------------------------CHC------------------------------//
typedef int ARRAY[7][8];
const int d[2][2] = { 0, 1, 1, 0 };
int G[7][8], cnt;
bool vis[7][8], used[28 + 1];
int ans[7][8];
int Bone[7][7];
int kase = 1;
void pre() {
for (int i = 0, k = 0; i < 7; ++i)
for (int j = i; j < 7; ++j)
Bone[i][j] = ++k;
}
bool check(int r) {
for (int i = 0; i < 8; ++i)
if (vis[r][i] == false)
return false;
return true;
}
void print(ARRAY arr) {
for (int i = 0; i < 7; ++i) {
for (int j = 0; j < 8; ++j)
printf("%4d", arr[i][j]);
puts("");
}
}
bool inside(int x, int y) { return x >= 0 && x < 7 && y >= 0 && y < 8; }
void dfs(int x, int y, int cur) {
if (cur == 28) {
++cnt;
print(ans);
puts("");
return;
}
if (y > 7) {
if (!check(x)) return;
dfs(x + 1, 0, cur);
return;
}
if (vis[x][y]) {
dfs(x, y + 1, cur);
return;
}
for (int i = 0; i < 2; ++i) {
int nx = x + d[i][0], ny = y + d[i][1];
if (!inside(nx, ny)) continue;
if (vis[nx][ny]) continue;
int a = G[x][y], b = G[nx][ny];
if (a > b) swap(a, b);
int bone = Bone[a][b];
if (!used[bone]) {
vis[x][y] = vis[nx][ny] = used[bone] = true;
ans[x][y] = ans[nx][ny] = bone;
dfs(x, y + 1 + d[i][1], cur + 1);
vis[x][y] = vis[nx][ny] = used[bone] = false;
}
}
}
int main() {
pre();
while (~scanf("%d", &G[0][0])) {
if (kase > 1) printf("\n\n\n");
CLEAR(vis, 0);
CLEAR(used, 0);
for (int i = 1; i < 8; ++i) scanf("%d", &G[0][i]);
for (int i = 1; i < 7; ++i)
for (int j = 0; j < 8; ++j)
scanf("%d", &G[i][j]);
printf("Layout #%d:\n\n", kase);
print(G);
cnt = 0;
printf("\nMaps resulting from layout #%d are:\n\n", kase);
dfs(0, 0, 0);
printf("There are %d solution(s) for layout #%d.\n", cnt, kase++);
}
return 0;
}