|
439-Knight Moves |
13381 |
56.27% |
5157 |
93.21% |
Question link:
Http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & category = 105 & page = show_problem & problem = 380
Question type: Search
Sample input:
e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6
Sample output:
To get from e2 to e4 takes 2 knight moves.To get from a1 to b2 takes 4 knight moves.To get from b2 to c3 takes 2 knight moves.To get from a1 to h8 takes 6 knight moves.To get from a1 to h7 takes 5 knight moves.To get from h8 to a1 takes 6 knight moves.To get from b1 to c3 takes 1 knight moves.To get from f6 to f6 takes 0 knight moves.
Analysis:
This is also a very classic search entry question. Because the question is to specify the start position and target position of the chess horse, it is required that the horse go to the target location with the least number of steps. BFS is generally recommended for finding the minimum number of steps.
When calculating the number of steps, there is a small trick: open a vis array, initialize to 0, and then this is used to record the number of steps, not just to mark whether or not the walk. For details, see the code.
# Include <iostream> # include <cstdio> # include <cstring> using namespace STD; char start [3], end [3]; int dir [8] [2] = {-}, {-}, {2,-1}, {1, -2 },{-1,-2 },{-2,-1 }}; int vis [10] [10]; struct node {int X, Y ;}; node que [1000]; void BFS () {int front = 0, rear = 1; que [0]. X = start [0]-'A', que [0]. y = start [1]-'0'-1; vis [que [0]. x] [que [0]. y] = 1; while (front <rear) {node T = que [Front ++]; // if conditions are met, the IF (T. X = = End [0]-'A' & T. y = end [1]-'0'-1) {printf ("to get from % s to % s takes % d knight moves. \ n ", start, end, vis [T. x] [T. y]-1); Return ;}for (INT I = 0; I <8; ++ I) {int dx = T. X + dir [I] [0], dy = T. Y + dir [I] [1]; If (dx> = 0 & DX <8 & dy> = 0 & dy <8 &&! Vis [dx] [dy]) {vis [dx] [dy] = vis [T. x] [T. y] + 1; // remember the number of steps node temp; temp. X = DX, temp. y = Dy; que [rear ++] = temp ;}}} int main () {# ifdef local freopen ("input.txt", "r", stdin ); # endif while (~ Scanf ("% S % s", start, end) & start [0]) {memset (VIS, 0, sizeof (VIS); BFS ();} return 0 ;}