Knight Moves (UVa 439) BFS

Source: Internet
Author: User

Title: Https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=839&page=show_ problem&problem=380

Idea: Use BFS to find the shortest distance to the end.

Tip: Use a dir array and two for loops to enumerate the eight nodes connected to one node.

/*Knight Moves (UVa 439)*/#include<iostream>#include<cstring>#include<queue>using namespacestd;Const intMAXN =Ten;structpoint{intR, c, CNT; Point (intRintCintcnt): R (R), C (c), CNT (CNT) {}};intVIS[MAXN][MAXN]; intDir[] = {1,-1,2,-2};intR1, C1, R2, C2;//coordinates of the start and end pointsintBFS (intX1,intY1,intX2,inty2);intMain () {//freopen ("Input.txt", "R", stdin);    Chars1[2], s2[2];  while(Cin >> S1 >>S2) {R1= s1[1] -'0'; C1= s1[0] -'a'+1; R2= s2[1] -'0'; C2= s2[0] -'a'+1; cout<<"To get from"<< S1 <<" to"<< S2 <<"takes"<< BFS (R1, C1, R2, C2) <<"Knight moves."<<Endl; }         return 0;}intBFS (intX1,intY1,intX2,inty2) {memset (Vis,0,sizeof(VIS)); Queue<Point>Q; Q.push (Point (x1, y1,0)); VIS[X1][Y1]=1;  while(!Q.empty ()) {Point U=Q.front ();        Q.pop (); if(U.R = = R2 && u.c = =C2)returnu.cnt;  for(intI=0; i<4; i++) {//join a walk-in node to a queue             for(intj=0; j<4; J + +){                if(I! = J &&-dir[i]! =Dir[j]) {Point V (U.R+dir[i], u.c+dir[j], u.cnt+1); if(v.r>=1&& v.r<=8&& v.c>=1&& v.c<=8&& vis[v.r][v.c]==0) {Q.push (v); VIS[V.R][V.C]=1; }                }            }        }    }}

Knight Moves (UVa 439) BFS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.