/**
* 回溯算法
*
* 約瑟芬殺人問題
* */
public class Josephus {
private static int N = 20;
private static int M = 5; //數到M就咔嚓一個人
class Node{
int val; //下標
Node next;
public Node(int val){
this.val = val;
}
}
public void killNode(){
Node header = new Node(1); //第一個結點
Node x = header; //目前被點到的人
for(int i = 2;i <= N;i++){
x = (x.next = new Node(i));
}
x.next = header; //頭尾相接
System.out.println("被咔擦的順序爲:");
while(x != x.next){
//至少還有兩人 仍然繼續報數,咔擦
for(int i = 1;i < M;i++){
x = x.next;
}
System.out.println(x.next.val + "被咔擦了");
x.next = x.next.next;
}
System.out.println("最後的幸運兒是:" + x.val);
}
public static void main(String[] args){
Josephus j = new Josephus();
j.killNode();
}
}