Title: poj 2488 a knight's journey
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 2488
Solution Type: backtrackingAlgorithm
Author: Liu yaning
Give the size of a board, judge whether a horse can walk through all cells without repeating, and record one of the steps.
Question: Classic backtracking, not very special. The special point is to record the steps. If the steps are successful, the steps in this step are recorded. Otherwise, no records are recorded.
Submission: no error submission record.
Note:CodeThere are still many inconciseness points in this article. Please advise and correct them.
SourceProgram:
# Include <iostream>
# Include <string>
# Include <cstdio>
Using namespace STD;
Int map [30] [30], C, R, num;
String ans;
Int DFS (int I, Int J)
{
If (Map [I] [J]) return 0;
Num ++;
Ans + = I;
Ans + = J;
Map [I] [J] = 1;
If (num = r * c) return 1;
If (I-2> = 1 & J-1> = 1 & DFS (I-2, J-1) return 1;
Else if (I-2> = 1 & J + 1 <= C & DFS (I-2, J + 1) return 1;
Else if (I-1> = 1 & J-2> = 1 & DFS (I-1, J-2) return 1;
Else if (I-1> = 1 & J + 2 <= C & DFS (I-1, J + 2) return 1;
Else if (I + 1 <= R & J-2> = 1 & DFS (I + 1, J-2) return 1;
Else if (I + 1 <= R & J + 2 <= C & DFS (I + 1, J + 2) return 1;
Else if (I + 2 <= R & J-1> = 1 & DFS (I + 2, J-1) return 1;
Else if (I + 2 <= R & J + 1 <= C & DFS (I + 2, J + 1) return 1;
Ans. Resize (ANS. Size ()-2 );
Map [I] [J] = 0;
Num --;
Return 0;
}
Int main ()
{
Long casenum, I;
Cin> casenum;
For (I = 1; I <= casenum; I ++)
{
Cout <"Scenario #" <I <":" <Endl;
Num = 0;
Memset (MAP, 0, sizeof (MAP ));
Ans = "";
Cin> C> r;
If (DFS (1, 1 ))
{
For (Int J = 0; j <ans. Size (); j ++)
{
If (J % 2) ans [J] + = '0 ';
Else ans [J] + = 'a'-1;
}
Cout <ans <Endl;
}
Else cout <"impossible" <Endl;
}
Return 0;
}