同学玩游戏的时候碰到的事,有六个字母ELPHME,
规定只能第一个字母移动到第四个(第二到第四个字母前进),或者最后一个字母移动到第二个(第二个以后的字母后退),目的是把这六个字母重组为HELPME,
暂不限步数,求教思路

表达不合理之处,敬请指出
------解决方案--------------------
先说下大概的理解吧,
第一个字母移动到第四个 这是 在调整 help的顺序
最后一个字母移动到第二个 这个是往“help”中加入E字符,
这个题目比较有意思,回头好好研究下
------解决方案--------------------
StringBuffer sb=new StringBuffer("ELPHME");
sb.insert(0, sb.toString().charAt(3)).delete(4, 5)
;
System.out.println(sb.toString());
------解决方案--------------------
哈,那怎么处理呢。字符移位
------解决方案--------------------
队列做广度搜索,每个元素是一个状态,每个状态可以产生2个新状态,用一个map记录出现过的状态,避免重复搜索。
既然是广度搜索,最先发现的答案就是最快的答案,因为经历的步骤最少。
------解决方案--------------------
这是另外一个帖子的问题吧。。
------解决方案--------------------
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
class Node {
static ArrayList<Node> prev=new ArrayList<Node>(), next=new ArrayList<>();
static String init, target;
static HashSet<String> set=new HashSet<String>();
String str;
ArrayList<String> queue;
Node(String str) {
this.str=str;
queue=new ArrayList<String>();
set.add(str);
}
Node(Node parent, String method) {
str=parent.handle(method);
if (set.add(str)) {
queue=new ArrayList<>(parent.queue);
queue.add(method+str);
check();
}
}
public void check() {
if (target.equals(str)) {
System.out.println(queue);
System.exit(0);
}
}
public String handle(String method) {
if ("1 ".equals(method)) {
//第一个字母移动到第四个(第二到第四个字母前进)
return str.substring(1,4)+str.substring(0,1)+str.substring(4);
}
if ("2 ".equals(method)) {
//最后一个字母移动到第二个(第二个以后的字母后退)
return str.substring(0,1)+str.substring(5,6)+str.substring(1,5);
}
return null;
}
public static void addChild(Node parent) {
next.add(new Node(parent,"1 "));
next.add(new Node(parent,"2 "));
}
@SuppressWarnings("unused")
public static void main(String[] args) {
init="mephel";
target="helpme";
Node root=new Node(init);
next.add(root);
do {
prev=next;
next=new ArrayList<>();
for (Node node : prev) {
addChild(node);
}
} while (!next.isEmpty());
}
}