马踏棋盘:贪心算法java实现

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

class Horse {
	private boolean board[][] = new boolean[8][8];//棋盘
	private LinkedList steps = new LinkedList();//马儿的足迹
	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 list = foundNext(p);
		
		for (int i = 0; i < list.size(); i++) {
			int n = countNext(list.get(i));
			if(n0){
					best = list.get(i);
					temp = n;
				}
				else if(n==0&&steps.size()==63)
					//最后一步时候n等于0,但是也要记录当前节点
					best = list.get(i);				
			}
		}
		return best;
	}
	private ArrayList foundNext(Point p){//获取某点的出口
		ArrayList list = new ArrayList();
		for(int i =0; i=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 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();
		}
	}
}

你可能感兴趣的:(java,贪心算法,算法)