zoukankan      html  css  js  c++  java
  • uva 439 Knight Moves 骑士移动

    这道题曾经写过,bfs。用队列,不多说了,上代码:

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<queue>
    using namespace std;
    int map[10][10];
    int visit[10][10];
    int dist[10][10];
    int dx[8]={-2,-2,-1,-1,1,1,2,2};
    int dy[8]={-1,1,-2,2,-2,2,-1,1}; 
    char a[5];
    int x2,y2;
    struct node
    {
    	int x,y;
    };
    queue<node>q; 
    int bfs(node T)
    {
    	if(T.x==x2&&T.y==y2)
    	{
    		return dist[T.x][T.y];
    	}
    	else
    	{
    		while(!q.empty())
    		{
    			node m = q.front();
    			q.pop();
    			if(m.x==x2&&m.y==y2)
    				return dist[m.x][m.y];
    			for(int i=0; i<8; i++)
    			{
    				
    				int xx = m.x+dx[i];
    				int yy = m.y+dy[i];
    				if(!visit[xx][yy]&&xx>0&&yy>0&&xx<=8&&yy<=8)
    				{
    					node n ;
    					n.x = xx;
    					n.y = yy;
    					q.push(n);
    					dist[xx][yy] = dist[m.x][m.y]+1;
    					visit[xx][yy] = 1;
    				}
    			}
    		}
    	}
    }
    int main()
    {
    	int x1,y1,i,j;
    	while(gets(a))
    	{
    		y1 = a[0]-'a'+1;
    		x1 = a[1]-'0';
    		y2 = a[3]-'a'+1;
    		x2 = a[4]-'0';
    		//printf("%d %d %d %d
    ",x1,y1,x2,y2);
    		node T;
    		T.x = x1;
    		T.y = y1;
    		memset(dist,0,sizeof(dist));
    		memset(visit,0,sizeof(visit));
    		q.push(T);
    		bfs(T);
    		printf("To get from %c%c to %c%c takes %d knight moves.
    ",a[0],a[1],a[3],a[4],dist[x2][y2]);
    		while(!q.empty())
    		{
    			q.pop();
    		} 
    	}
    	return 0;
    }
     


  • 相关阅读:
    关于prototype属性的理解
    关于js中原型链的理解
    关于焦点轮播图的优化
    两个动画函数的分析
    JavaScript 实用技巧和写法建议
    Vue SPA 首屏加载优化实践
    带你优雅的使用 icon
    前端本地文件操作与上传
    学习webpack
    Vue 脱坑记
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6895347.html
Copyright © 2011-2022 走看看