HDU 1372 (BFS)

Source: Internet
Author: User

BFS:

Start Point;

Start search:

When reading the first and leaving the team, the search range is four or eight points (some do not exist). The searched points are in the queue and the duration is + 1 until the read point is equal to the end point;

15 MS 372 K

Code:

#include <iostream>#include <string>#include <cstdio>#include <queue>using namespace std;struct point{int x;int y;int step;}st,ed;int x1,y1,x2,y2;bool visit[10][10];int xx[8] = {1,2,1,2,-1,-2,-1,-2};int yy[8] = {2,1,-2,-1,2,1,-2,-1};void bfs(){memset(visit,false,sizeof(visit));st.x = x1;st.y = y1;st.step = 0;queue <point> p;p.push(st);while(!p.empty()){ed = p.front();p.pop();if(ed.x == x2 && ed.y == y2)break;for(int i = 0; i < 8; i++){st.x = ed.x + xx[i];st.y = ed.y + yy[i];st.step = ed.step + 1;if(!visit[st.x][st.y]&&st.x>0&&st.x<9&&st.y>0&&st.y<9){visit[st.x][st.y] = true;p.push(st);}}}}int main(){char c1,c2,c;while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF){x1 = c1 - 'a' + 1;x2 = c2 - 'a' + 1;bfs();printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,ed.step);getchar();}}

DFS:

Perform 8 Class-Oriented Access to each vertex from the starting point and call DFS recursively. The complexity is high. This question is only 8x8, so it is acceptable;

375 MS 332 K

Code:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <iomanip>using namespace std;int r[8][2]={{2,1},{1,2},{-1,2},{-2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1} };int num[10][10];void dfs(int x1, int y1, int move){if(x1<=0 || x1>=9 || y1<=0 || y1>=9||move>=num[x1][y1])return ;num[x1][y1] = move;for(int i = 0; i < 8; i++){dfs(x1+r[i][0], y1+r[i][1],move+1);}}int main(int argc, char *argv[]){int x1,y1,x2,y2;char c1,c2,c;while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF){x1 = c1 - 'a' + 1;x2 = c2 - 'a' + 1;memset(num,100,sizeof(num));dfs(x1,y1,0);printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,num[x2][y2]);getchar();}return 0;}

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.