蓝桥杯 跳蚂蚱

题目


题目描述:


有9只盘子,排成1个圆圈。 其中8只盘子内装着8只蚱蜢,有一个是空盘。 我们把这些蚱蜢顺时针编号为 1~8 每只蚱蜢都可以跳到相邻的空盘中,也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。 请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列, 并且保持空盘的位置不变(也就是1-8换位,2-7换位,…),至少要经过多少次跳跃?

输入:
输出:
样例输入
 
    
样例输出



思路


以空盘子进行广搜,得到的结果为答案



代码

package text;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;

public class Main {

	public static class loc {
		int x;
		int step;
		int pos[] = new int[9];
		loc(){
		}
	}
	static int forward[] = { -2, -1 ,1 ,2};
    public static void main(String[] args) {
    	Set<String> vis = new TreeSet();
    	loc zero =new loc();
    	zero.x = 8;
    	zero.step = 0;    
    	for(int i=0;i<9;i++) {
    		zero.pos[i]=i;
    	}
    	String w=new String();
		for(int j=0;j<9;j++) {
			w+=Integer.toString(zero.pos[j]);
		}
		vis.add(w);
    	Queue<loc> queue =new LinkedList<loc>();
    	queue.add(zero);
    	while(!queue.isEmpty()) {
    		loc s=queue.remove();
//			System.out.println(step);
    		if(s.pos[0]==8&&s.pos[1]==7&&s.pos[2]==6&&s.pos[3]==5&&s.pos[4]==4&&s.pos[5]==3&&s.pos[6]==2&&s.pos[7]==1&&s.pos[8]==0) {
    			System.out.println(s.step);
    			return;
    		}
    		else {
    			for(int i=0;i<4;i++) {
    				int tx=s.x+forward[i];
    				loc t = new loc();
    				if(tx<0) {
    					tx=tx+9;
    				}
    				else if(tx>8) {
    					tx=tx-9;
    				}   				
    				for(int j=0;j<9;j++) {
    					t.pos[j]=s.pos[j];
    				}
    				int temp=t.pos[tx];
    				t.pos[tx]=t.pos[s.x];
    				t.pos[s.x]=temp;
    				String str="";
    				for(int j=0;j<9;j++) {
    					str+=Integer.toString(t.pos[j]);
    				}
    				if(!vis.contains(str)) {
    					t.step=s.step+1;
    					t.x=tx;
//    					System.out.println(str);
    					queue.add(t);
    					vis.add(str);
    				}
    				}
    		}
    	}
    
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值