您的位置:首页 > 其它

B - A Dicey Problem UVA - 810

2018-01-29 10:21 302 查看
#include <iostream>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <string>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
struct road {
int x, y;
}t, b[12000];
int m, n, sx, sy, stop, etop,siz, a[15][15];
bool flag[15][15][7][7], f;
int cx[] = { -1,1,0,0 };
int cy[] = { 0,0,-1,1 };
int dir[] = {3,4,1,2};
int fx[] = {0,6,5,4,3,2,1};
//  1 2 3 4 5 6
int nativepos[][7] = {{ 0,0,0,0,0,0,0 },
/*1*/		 { 0,0,3,5,2,4,0 },
{ 0,4,0,1,6,0,3 },
{ 0,2,6,0,0,1,5 },
{ 0,5,1,0,0,6,2 },
{ 0,3,0,6,1,0,4 },
/*6*/		 { 0,0,4,2,5,3,0 }
};
queue<road> q;
void changetop(int &ntop,int &behind,int dir) {//1 left 2 right 3 up 4 down
if (dir == 1) {
ntop = nativepos[ntop][behind];
}
else if (dir == 2) {
ntop = nativepos[ntop][fx[behind]];
}
else if (dir == 3) {
int t = ntop;
ntop = behind;
behind = fx[t];
}
else{
int t = ntop;
ntop = fx[behind];
behind = t;
}
}
void dfs(int x,int y,int ntop,int behind){
if (x == sx && y == sy && siz != 0) {
if (q.empty()) {
for (int i = 0; i < siz; ++i) {
q.push(b[i]);
}
t.x = x, t.y = y;
q.push(t);
}
else {
int s = q.size();
if (s > siz) {
while (!q.empty()) {
q.pop();
}
for (int i = 0; i < siz; ++i) {
q.push(b[i]);
}
t.x = x, t.y = y;
q.push(t);
}
}
f = true;
return;
}
b[siz].x = x, b[siz++].y = y;
flag[x][y][ntop][behind] = true;
for (int i = 0; i < 4; ++i) {
int x0 = x + cx[i];
int y0 = y + cy[i];
if (x0 <= 0 || y0 <= 0 || x0 > m || y0 > n || a[x0][y0] == 0) {
continue;
}
int ctop = ntop, cbehind = behind;
changetop(ctop, cbehind, dir[i]);
if (a[x0][y0] == -1 || ntop == a[x0][y0]) {
if (flag[x0][y0][ctop][cbehind] && (x0 != sx || y0 != sy)) {
continue;
}
dfs(x0, y0, ctop, cbehind);
}
}
flag[x][y][ntop][behind] = false;
siz--;
}
int main() {
string names;
while (cin >> names) {
if (names == "END") {
break;
}
cin >> m >> n >> sx >> sy >> stop >> etop;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
scanf("%d", &a[i][j]);
}
}
memset(flag, false, sizeof(flag));
f = false;
siz = 0;
dfs(sx, sy, stop, etop);
if (f) {
cout << names;
int c = 10, s = q.size();
f = false;
while (s != 1) {
t = q.front();
q.pop();
if (c > 9) {
c = 1;
printf("\n  ");
}
printf("(%d,%d),", t.x, t.y);
c++;
s--;
}
t = q.front();
q.pop();
if (c > 9) {
c = 1;
printf("\n  ");
}
printf("(%d,%d)\n", t.x, t.y);
}
else {
cout << names << endl;
cout << "  No Solution Possible" << endl;
}
}
return 0;
}
dfs深搜。对同一路径,已走过的点(x,y),及其到达该点时正方体状态(top,behind)(顶部数字及前部数字可确定正方体),根据此四者确定该状态已走过,之后如果在该正方体状态则不需要走过该点,因为如果再走过该点之后可以找到一条路径到达终点,此时该路径不是最短的。

另外对于正方体状态的改变可根据正方体投top,behind找出一定规律,重点是将6个不同的top状态时的正方体平面展开,左右翻转时可根据逆时针确定之后的top,前后翻转时可根据当前的top,behind改变状态。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: