1. 程式人生 > >馬踏棋盤:貪心演算法java實現

馬踏棋盤:貪心演算法java實現

import java.util.ArrayList;
import java.util.LinkedList;

class Horse {
	private boolean board[][] = new boolean[8][8];//棋盤
	private LinkedList<Point> steps = new LinkedList<Point>();//馬兒的足跡
	private Point vector[] = new Point[]{new Point(1,2),new Point(-1,-2),
			new Point(-1,2),new Point(1,-2),new Point(2,1),
			new Point(-2,-1),new Point(-2,1),new Point(2,-1)};//走下一步的增量
	
	public void start(Point start){
		System.out.println();
		System.out.println("從"+start.toString()+"開始尋找。。。。");
		goTo(start);
		while(true){
			Point temp = getBestNext(steps.getLast());
			if(temp.getX()==-1)
				break;//結束或失敗
			else
				goTo(temp);
		}
		displayboard();
	}
	private void goTo(Point p){//去下一步
		steps.add(p);
		board[p.getX()][p.getY()] = true;
	}
	private Point getBestNext(Point p){
		int temp =9;
		Point best = new Point();
		
		ArrayList<Point> list = foundNext(p);
		
		for (int i = 0; i < list.size(); i++) {
			int n = countNext(list.get(i));
			if(n<temp){
				if(n>0){
					best = list.get(i);
					temp = n;
				}
				else if(n==0&&steps.size()==63)
					//最後一步時候n等於0,但是也要記錄當前節點
					best = list.get(i);				
			}
		}
		return best;
	}
	private ArrayList<Point> foundNext(Point p){//獲取某點的出口
		ArrayList<Point> list = new ArrayList<Point>();
		for(int i =0; i<vector.length;i++){
			Point temp = new Point();
			int x = p.getX()+vector[i].getX();
			int y = p.getY()+vector[i].getY();
			if(x>=0&&x<8&&y>=0&&y<8){
				temp.setX(x);
				temp.setY(y);
				if(!check(temp)){
					list.add(temp);
				}
			}
		}
		return list;
	}
	private int countNext(Point p){//獲取某點的出口數
		ArrayList<Point> list = foundNext(p);
		return list.size();
	}
	private boolean check(Point p){//檢視該點是否已經走過
		return board[p.getX()][p.getY()];
	}
	
	private void displayboard(){//輸出結果
		boolean issucc = true;
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				issucc = issucc&&board[i][j];
			}
		}
		if(steps.size()==64&&issucc)
			System.out.println("尋找成功,結果");
		else
			System.out.println("失敗,結果如下");
		for (int i = 0; i < steps.size(); i++) {
			System.out.print(steps.get(i).toString()+"  ");
			if((i+1)%10==0)
				System.out.println();
		}
	}
}