icfp-solver/src/main/java/ru/bosony/solvers/DijkstraSolver.java
author indvdum (gotoindvdum[at]gmail[dot]com)
Mon, 16 Jul 2012 18:58:08 +0400
branchCleverSearch
changeset 47 b3d48e364f9e
parent 46 4197f736166a
child 50 9530f55e9639
permissions -rw-r--r--
Moar
     1 package ru.bosony.solvers;
     2 
     3 import java.util.ArrayList;
     4 import java.util.HashMap;
     5 import java.util.HashSet;
     6 import java.util.List;
     7 import java.util.Map;
     8 import java.util.Set;
     9 
    10 import ru.bosony.graph.CellsLink;
    11 import ru.bosony.graph.CellsLinkTransformer;
    12 import ru.bosony.model.cellscontents.CellContent;
    13 import ru.bosony.model.game.Game;
    14 import ru.bosony.model.game.GameState;
    15 import ru.bosony.model.mine.Cell;
    16 import ru.bosony.model.mine.Mine;
    17 import ru.bosony.model.moving.Movement;
    18 import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
    19 import edu.uci.ics.jung.graph.DirectedSparseGraph;
    20 import edu.uci.ics.jung.graph.Graph;
    21 
    22 /**
    23  * @author indvdum (gotoindvdum[at]gmail[dot]com) <br>
    24  *         16.07.2012 11:05:26
    25  * 
    26  */
    27 public class DijkstraSolver extends AbstractSolver {
    28 
    29 	protected Map<String, Set<Movement>>	loseMovs	= new HashMap<String, Set<Movement>>();
    30 	protected Set<CellsLink>				loseLinks	= new HashSet<CellsLink>();
    31 
    32 	public DijkstraSolver(Mine mine, SolverListener listener) {
    33 		super(mine, listener);
    34 	}
    35 
    36 	@Override
    37 	public void solve() {
    38 		while (true) {
    39 			Mine testMine = null;
    40 			try {
    41 				testMine = mine.clone();
    42 			} catch (CloneNotSupportedException e1) {
    43 				throw new RuntimeException(e1);
    44 			}
    45 			Game game = new Game(testMine);
    46 
    47 			while (game.getState() == GameState.Game) {
    48 				String map = testMine.toText();
    49 				if (!loseMovs.containsKey(map)) {
    50 					loseMovs.put(map, new HashSet<Movement>());
    51 				}
    52 				Set<Cell> targets = testMine.findCells(CellContent.Lambda);
    53 				targets.addAll(testMine.findCells(CellContent.HighOrderRock));
    54 				if (targets.size() == 0)
    55 					targets = testMine.findCells(CellContent.OpenLambdaLift);
    56 				Graph<Cell, CellsLink> graph = getDirectedGraph(testMine);
    57 				DijkstraShortestPath<Cell, CellsLink> alg = new DijkstraShortestPath<Cell, CellsLink>(graph,
    58 						new CellsLinkTransformer<CellsLink, Double>());
    59 				Cell nextTarget = null;
    60 				List<CellsLink> routeToNextTarget = null;
    61 				double shortestDist = Double.MAX_VALUE;
    62 				for (Cell target : targets) {
    63 					if (target == null)
    64 						continue;
    65 					List<CellsLink> route = null;
    66 					Number dist = null;
    67 					try {
    68 						route = alg.getPath(testMine.getRobotCell(), target);
    69 						dist = alg.getDistance(testMine.getRobotCell(), target);
    70 					} catch (IllegalArgumentException e) {
    71 						// hmmm...
    72 						continue;
    73 					}
    74 					if (dist != null && route != null && route.size() > 0 && dist.doubleValue() < shortestDist) {
    75 						CellsLink firstLink = route.get(0);
    76 						Movement mov = firstLink.getSource().getCoordinate()
    77 								.getNecessaryMovement(firstLink.getTarget().getCoordinate());
    78 						if (!loseMovs.get(map).contains(mov)) {
    79 							shortestDist = dist.doubleValue();
    80 							nextTarget = target;
    81 							routeToNextTarget = route;
    82 							break;
    83 						}
    84 					}
    85 				}
    86 				if (nextTarget != null) {
    87 					for (CellsLink link : routeToNextTarget) {
    88 						Cell source = link.getSource();
    89 						Cell target = link.getTarget();
    90 						if (isSafeMovement(testMine, source, target)) {
    91 							Movement mov = source.getCoordinate().getNecessaryMovement(target.getCoordinate());
    92 							GameState state = game.move(mov);
    93 							if (state == GameState.Lose || state == GameState.Abort || game.hasViciousCircle()) {
    94 								loseMovs.get(map).add(mov);
    95 								loseLinks.add(link);
    96 							}
    97 						}
    98 						break;
    99 					}
   100 				} else {
   101 					for (Movement mov : Movement.values()) {
   102 						if (!loseMovs.get(map).contains(mov)) {
   103 							GameState state = game.move(mov);
   104 							if (state == GameState.Lose || state == GameState.Abort || map.equals(testMine.toText())
   105 									|| game.hasViciousCircle())
   106 								loseMovs.get(map).add(mov);
   107 							break;
   108 						}
   109 					}
   110 				}
   111 			}
   112 			if (game.getState() == GameState.Win) {
   113 				addNewRoute(game.getStringRoute(), game.getScore());
   114 			}
   115 			attemptsCount++;
   116 		}
   117 	}
   118 
   119 	protected boolean isSafeMovement(Mine mine, Cell source, Cell target) {
   120 		if (source == null || target == null)
   121 			return false;
   122 		if (source.getContent().getTrampolineTarget() == target.getContent())
   123 			return true;
   124 		Cell upCell = mine.getCell(target.getCoordinate().up());
   125 		if (upCell == null)
   126 			return true;
   127 		Cell upUpCell = mine.getCell(target.getCoordinate().up().up());
   128 		Cell upUpLeftCell = mine.getCell(target.getCoordinate().up().up().left());
   129 		Cell upUpRightCell = mine.getCell(target.getCoordinate().up().up().right());
   130 		if (upCell.getContent() == CellContent.Empty
   131 				&& (upUpCell != null
   132 						&& (upUpCell.getContent() == CellContent.Rock || upUpCell.getContent() == CellContent.HighOrderRock)
   133 						|| upUpLeftCell != null
   134 						&& (upUpLeftCell.getContent() == CellContent.Rock || upUpLeftCell.getContent() == CellContent.HighOrderRock) || upUpRightCell != null
   135 						&& (upUpRightCell.getContent() == CellContent.Rock || upUpRightCell.getContent() == CellContent.HighOrderRock))) {
   136 			return false;
   137 		}
   138 		return true;
   139 	}
   140 
   141 	protected Graph<Cell, CellsLink> getDirectedGraph(Mine mine) {
   142 		Graph<Cell, CellsLink> graph = new DirectedSparseGraph<Cell, CellsLink>();
   143 		for (CellsLink link : getCellLinks(mine)) {
   144 			graph.addEdge(link, link.getSource(), link.getTarget());
   145 		}
   146 		return graph;
   147 	}
   148 
   149 	protected List<CellsLink> getCellLinks(Mine mine) {
   150 		List<CellsLink> links = new ArrayList<CellsLink>();
   151 		Cell robotCell = mine.getRobotCell();
   152 		findAllCellLinks(mine, robotCell, links, new HashSet<Cell>());
   153 		return links;
   154 	}
   155 
   156 	protected void findAllCellLinks(Mine mine, Cell cell, List<CellsLink> links, Set<Cell> processedCells) {
   157 		if (processedCells.contains(cell))
   158 			return;
   159 		else
   160 			processedCells.add(cell);
   161 		for (Cell neighboringCell : mine.getAdjacentCells(cell)) {
   162 			if (neighboringCell == null)
   163 				continue;
   164 			CellContent neighboringContent = neighboringCell.getContent();
   165 			if (neighboringContent == CellContent.Earth || neighboringContent == CellContent.Empty
   166 					|| neighboringContent == CellContent.HuttonsRazor || neighboringContent == CellContent.Lambda
   167 					|| neighboringContent == CellContent.OpenLambdaLift) {
   168 				if (isSafeMovement(mine, cell, neighboringCell)) {
   169 					CellsLink link = new CellsLink(mine, cell, neighboringCell);
   170 					if (!loseLinks.contains(link)) {
   171 						links.add(link);
   172 						findAllCellLinks(mine, neighboringCell, links, processedCells);
   173 					}
   174 				}
   175 			} else if (!CellContent.getTargets().contains(cell.getContent())
   176 					&& CellContent.getTargets().contains(neighboringContent)) {
   177 				findAllCellLinks(mine, neighboringCell, links, processedCells);
   178 			}
   179 		}
   180 		if (CellContent.getTrampolines().contains(cell.getContent())) {
   181 			for (Cell target : mine.findCells(cell.getContent().getTrampolineTarget())) {
   182 				if (target == null)
   183 					continue;
   184 				if (isSafeMovement(mine, cell, target)) {
   185 					CellsLink link = new CellsLink(mine, cell, target);
   186 					if (!loseLinks.contains(link)) {
   187 						links.add(link);
   188 						findAllCellLinks(mine, target, links, processedCells);
   189 					}
   190 				}
   191 			}
   192 		}
   193 	}
   194 }