sicily 1152 1153 马的周游

之前发过一篇1152的,后来做1153发现找不到一条回路。。郁闷,只好循规蹈矩。

思路:

1.深搜,无优化,TL;

2.加上对每次游走时的分析,先走入度较小的点,我认为这样可以快速排除不能走的点。

#include <iostream> #include <cstring> #include <map> using namespace std; //#define COL 6 //#define ROW 5 #define COL 8 #define ROW 8 int n; int path[COL * ROW]; int move[8][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}}; int cur; int num[ROW][COL]; bool isVis[ROW][COL]; int degree[ROW][COL]; int degreeTmp[ROW][COL]; bool dfs() { if(cur == ROW * COL - 1) return true; int x = (path[cur] - 1) / COL; int y = (path[cur] - 1) % COL; multimap<int, int> suitNext; for(int i = 0; i < 8; i++) { int next_x = x + move[i][0]; int next_y = y + move[i][1]; if(next_x >= 0 && next_x < ROW && next_y >= 0 && next_y < COL && !isVis[next_x][next_y]) { degreeTmp[next_x][next_y]--; suitNext.insert(make_pair(degreeTmp[next_x][next_y], i)); } } for(multimap<int, int>::iterator iter = suitNext.begin(); iter != suitNext.end(); iter++) { int next_x = x + move[iter->second][0]; int next_y = y + move[iter->second][1]; isVis[next_x][next_y] = true; path[++cur] = num[next_x][next_y]; if(dfs()) return true; isVis[next_x][next_y] = false; cur--; degreeTmp[next_x][next_y]++; } return false; } void setNUM() { int a = 1; for(int i = 0; i < ROW; i++) { for(int j = 0; j < COL; j++) { num[i][j] = a++; } } } void setDegree() { memset(degree, 0, sizeof(degree)); for(int i = 0; i < ROW; i++) { for(int j = 0; j < COL; j++) { for(int k = 0; k < 8; k++) { int next_x = i + move[k][0]; int next_y = j + move[k][1]; if(next_x >= 0 && next_x < ROW && next_y >= 0 && next_y < COL) degree[next_x][next_y]++; } } } } int main() { setNUM(); setDegree(); while(cin >> n && n != -1) { path[0] = n; cur = 0; memset(isVis, false, sizeof(isVis)); memcpy(degreeTmp, degree, sizeof(degree)); isVis[(n - 1) / COL][(n - 1) % COL] = true; dfs(); bool isFirst = true; for(int i = 0; i < COL * ROW; i++) { if(isFirst) { cout << path[i]; isFirst = false; } else cout << " " << path[i]; } cout << endl; } return 0; } 

你可能感兴趣的:(sicily 1152 1153 马的周游)