package demo;
/**
* Algorithm Gossip: 三色棋
* 三色旗的问题最早由E.W.Dijkstra所提出,他所使用的用语为Dutch Nation Flag(Dijkstra为荷兰
* 人),而多数的作者则使用Three-Color Flag来称之。
* 假设有一条绳子,上面有红、白、蓝三种颜色的旗子,起初绳子上的旗子颜色并没有顺序,您
* 希望将之分类,并排列为蓝、白、红的顺序,要如何移动次数才会最少,注意您只能在绳子上
* 进行这个动作,而且一次只能调换两个旗子。
* @author gaoq
* @date 2015-5-13 下午10:55:36
*/
public class SanSeQi {
public static void main(String[] args) {
//假定:b-->蓝色,w-->白色,r-->红色
char[] data = new char[]{'a','w','r','b','b','r','w'};
System.out.println(new String(paixu(data)));
}
/**
* 排序
* @param data char数组
* @return char[]
*/
private static char[] paixu(char[] data){
int startIndex = 0;
int moveIndex = 0;
int endIndex = data.length-1;
while(moveIndex <= endIndex){
if(data[moveIndex] == 'b'){
exchangeIndex(data,startIndex,moveIndex);
startIndex ++;
}else if(data[moveIndex] == 'r'){
exchangeIndex(data,endIndex,moveIndex);
endIndex --;
}
moveIndex ++;
}
return data;
}
/**
* 独臂交换法
* @param data char数组
* @param idx1 下标1
* @param idx2 下标2
*/
private static void exchangeIndex(char[] data,int idx1,int idx2){
char temp = data[idx1];
data[idx1] = data[idx2];
data[idx2]=temp;
}
}
本文介绍了三色棋问题的解决方法,通过独臂交换法实现了绳子上三种颜色旗子从任意顺序调整到蓝、白、红的排列顺序,最小化了移动次数。
693

被折叠的 条评论
为什么被折叠?



