Ural1298 Knight classic DFS, ural1298dfs
This topic really misses a question that I did when I first started studying BFS. I remember it was POJ, and it was also Ma zhiri.
This topic is to give you a n * n board, starting from (0, 0), the way the horse walks through the day, whether the Board can be traveled, and each grid can only go once
Bfs was first written that day, but the record method opened a three-dimensional, and finally timed out. There was no way to change it to dfs, and then we kept WA, or RE didn't understand why, I have already completed my questions for two days. I have no good solutions. I finally knocked on the questions again and found out that I have passed! Looking for the previous code, we found that the dir array is different. It is really amazing that there are eight directions, and the order will be WA? Amazing questions
The procedure is simple. You can directly add DFS and mark it. You can use a container to record the path strength. Finally, you can find that the number of steps is n * n.
int n;int dir[8][2]={2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1};bool vis[10][10];vector<pair<int ,int > > G;int mark;int tot;void init() {memset(vis,false,sizeof(vis));mark = 0;G.clear();}bool input() {while(cin>>n) {return false;}return true;}int dfs(int x,int y,int step) {if(step == n * n){mark = 1;return step;}for(int i=0;i<8;i++) {int dx = x + dir[i][0];int dy = y + dir[i][1];if(dx < 0 || dx >= n || dy < 0 || dy >= n)continue;if(vis[dx][dy])continue;G.push_back(make_pair(dx,dy));vis[dx][dy] = true;dfs(dx,dy,step + 1);if(mark)return G.size();G.pop_back();vis[dx][dy] = false;}return 0;}void cal() {G.push_back(make_pair(0,0));tot++;vis[0][0] = true;dfs(0,0,1);if(!mark){puts("IMPOSSIBLE");return ;}for(int i=0;i<G.size();i++)printf("%c%d\n",G[i].first + 'a',G[i].second + 1);}void output() {}int main() {while(true) {init();if(input())return 0;cal();output();}return 0;}