马踏棋盘:贪心算法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();
		}
	}
}
    原文作者:贪心算法
    原文地址: https://blog.csdn.net/j12345678901/article/details/18606189
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞