her, positionWeight);
}
else
{
getAttemptPositions().add(positionWeight);
}
}
/**
* 计算花费的时间
*/
private int getSpendTime()
{
if (getAttemptPositions().contains(getPrincessPosition()))
{
int princessIndex = getAttemptPositions().indexOf(
getPrincessPosition());
PositionWeight princess = getAttemptPositions().get(princessIndex);
return princess.getSpendTime() <= time SUCCESS : FAIL;
}
return FAIL;
}
/**
* 从待尝试列表中查找总开销值最小的点(如果有几个相同开销的最小点,取靠近队尾的)
*
*/
private PositionWeight getMinPositionWeight()
{
PositionWeight minPositionWeight = getAttemptPositions().get(0);
for (PositionWeight positionWeight : getAttemptPositions())
{
if (minPositionWeight.getCost() >= positionWeight.getCost())
{
minPositionWeight = positionWeight;
}
}
return minPositionWeight;
}
/**
* 如果从父节点移动至子节点的G值小于子节点之前的G值(前提是子节点已经在开启列表中),则更新子节点的父节点及G值
*/
private void updateCostByFather(PositionWeight father,
PositionWeight subPosition)
{
int distanceOfAttemptFather = subPosition
.getDistanceFromAttemptFather(father);
int distanceOfPrince = father.getDistanceOfPrince()
+ distanceOfAttemptFather;
if (distanceOfPrince < subPosition.getDistanceOfPrince())
{
subPosition.updateByFather(father);
}
}
private MazeMap getMap()
{
return map;
}
private boolean isInPassedTable(PositionWeight positionWeight)
{
return getPassedPositions().contains(positionWeight);
}
private List getAttemptPositions()
{
return attemptPositions;
}
private List getPassedPositions()
{
return passedPositions;
}
private PositionWeight getPrincessPosition()
{
return princessPosition;
}
private void setPrincessPosition(PositionWeight princessPosition)
{
this.princessPosition = princessPosition;
}
private PositionWeight getPrincePosition()
{
return princePosition;
}
private void setPrincePosition(PositionWeight princePosition)
{
this.princePosition = princePosition;
}
}
单元测试类:
[java]
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
*
* 类名称:MazeTest 类描述: 创建人:dobuy
*
*/
public class MazeTest
{
private Maze maze;
private char[][] map;
/**
* 营救公主失败
*/
private final static int FAIL = -1;
/**
* 营救公主成功
*/
private final static int SUCCESS = 0;
/**
* testStart01 正常可达情况
*/
@Test
public void testStart01()
{
map = new char[][] { { '.', '.', '.', '.' }, { '.', '.', '.', '.' },
{ '.', '.', '.', '.' }, { 'S', '*', '*', 'P' } };
maze = new Maze(5, map);
assertEquals(maze.start(), SUCCESS);
}
/**
* testStart02 正常不可达情况
*/
@Test
public void testStart02()
{
map = new char[][] { { '.', '.', '.', '.' }, { '.', '.', '.', '.' },
{ '.', '.', '.', '.' }, { 'S', '*', '*', 'P' } };
maze = new Maze(2, map);
assertEquals(maze.start(), FAIL);
}
/**
* testStart03 参数异常
*/
@Test
public void testStart03()
{
map = null;
maze = new Maze(2, map);
assertEquals(maze.start(), FAIL);
map = new char[][] {};
maze = new Maze(2, map);
assertEquals(maze.start(), FAIL);
map = new char[][] { { '.', '.', '.', '.' }, { '.', '.', '.', '.' },
{ '.', '.', '.', '.' }, { '.', '.', '.', '.' } };
maze = new Maze(2, map);
assert