Title Address: 1936. Knight Moves
Ideas:
This problem at first did not understand test instructions ... orz ... Embarrassed, to see the great gods understand.
Test instructions is a 8*8 chess, the knight moves in the form of a horse ("Day" font), specify two points, output the smallest step.
can be solved with breadth search.
The specific code is as follows:
1#include <iostream>2#include <queue>3#include <cstring>4#include <string>5 using namespacestd;6 7 intDx[] = {-1, -2, -2, -1,1,2,2,1}; You can go in eight directions.8 intDy[] = {-2, -1,1,2,2,1, -1, -2};9 Ten BOOLvisited[ -]; One A intMain () { - intT; -CIN >>T; the while(t--) { -Memset (visited,false,sizeof(visited)); - intdistance[ -] = {0}; - + stringNode1, Node2; -CIN >> Node1 >>Node2; + A intX = (node1[0]-'a')*8+ node1[1]-'1'; at intY = (node2[0]-'a')*8+ node2[1]-'1'; - -queue<int>store; - Store.push (X); - while(!Store.empty ()) { - if(Store.front () = =Y) in Break; - to intx = Store.front ()/8; + inty = Store.front ()%8; - the for(inti =0; I <8; i++) { * intNX = x+Dx[i]; $ intNY = y+Dy[i];Panax Notoginseng - if(NX <0|| NX >7|| NY <0|| NY >7) the Continue; + inttemp = nx*8+NY; A the if(!Visited[temp]) { + Store.push (temp); -Visited[temp] =true; $Distance[temp] = Distance[store.front ()] +1; $ } - } - Store.pop (); the } -cout <<"To get from"<<Node1Wuyi<<" to"<< Node2 <<"takes" the<< Distance[y] <<"Knight moves.\n"; - } Wu - return 0; About } $
Sicily 1936. Knight Moves