ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

计蒜客:一维坐标的移动(java)

2022-01-14 15:04:20  阅读:150  来源: 互联网

标签:java int static 坐标 一维 new 计蒜客 public Yidong


运用bfs算法

  1. 在一个长度为n的坐标轴上,蒜头君想从A点 移动到B点。他的移动规则如下:
  2. 向前一步,坐标增加1。
  3. 向后一步,坐标减少1。
  4. 跳跃一步,使得坐标乘2。

蒜头君不能移动到坐标小于0或大于n的位置。蒜头想知道从A点移动到B点的最少步数是多少,你能帮他计算出来么?

输入格式

第一行输入三个整数n,A,B,分别代表坐标轴长度,起始点坐标,终点坐标。(0≤A,B≤n≤50000)

输出格式

输出一个整数占一行,代表蒜头要走的最少步数。

样例输入

10 2 7

样例输出

3

import java.util.*;
	class Yidong{
		int step = 0,x=0;
		public Yidong(){
			
		}
		public Yidong(int x,int step){
			this.x=x;
			this.step = step;
		}
	}
	public class Main {
	    static int n=0,A=0,B=0,result=0;
	    static int[] oprate = {1,-1,2};
	    static int[] visit = null;
		public static void main(String[] args) {
			// TODO Auto-generated method stub
	      Scanner sc = new Scanner(System.in);
	      n=sc.nextInt();
	      A=sc.nextInt();
	      B=sc.nextInt();
	      visit = new int[n+1];
	      bfs(A);
	      System.out.print(result);
		}
	    public static void bfs(int a){
	    	Queue<Yidong> queue = new LinkedList<Yidong>();
	    	visit[a] = 1;
	    	queue.offer(new Yidong(a,0));
	    	int flag = Math.abs(A-B);
	    	while(!queue.isEmpty()){
	    		Yidong temp = queue.poll();
	    		boolean find = false;
	    			for(int i=0;i<3;i++){
	    				if(i==2){
	    					if(temp.x*2<=n){
	    						if(temp.x*2==B){
	    							result = temp.step+1;
	    							find = true;
	    							break;
	    						}
	    						if(visit[temp.x*2]==0){
	    							visit[temp.x*2]=1;
	    							queue.offer(new Yidong(temp.x*2,temp.step+1));
	    						}
	    					}
	    				}else{
	    					if(temp.x+oprate[i]<=n){
	    						if(temp.x+oprate[i] == B){
	    							result = temp.step+1;
	    							find = true;
	    							break;
	    						}
	    						if(visit[temp.x+oprate[i]]==0){
	    							visit[temp.x+oprate[i]]=1;
	    							queue.offer(new Yidong(temp.x+oprate[i],temp.step+1));
	    						}
	    					}
	    				}
	    			}
	    		if(find){
	    			break;
	    		}
	    	}
	    }
	}

标签:java,int,static,坐标,一维,new,计蒜客,public,Yidong
来源: https://blog.csdn.net/weixin_57097732/article/details/122494689

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有