icfp-solver/src/main/java/ru/bosony/solvers/DijkstraSolver.java
author indvdum (gotoindvdum[at]gmail[dot]com)
Wed, 18 Jul 2012 01:25:43 +0400
branchCleverSearch
changeset 51 b431cec961d7
parent 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.Coordinate;
    18 import ru.bosony.model.moving.Movement;
    19 import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
    20 import edu.uci.ics.jung.graph.DirectedSparseGraph;
    21 import edu.uci.ics.jung.graph.Graph;
    22 
    23 /**
    24  * @author indvdum (gotoindvdum[at]gmail[dot]com) <br>
    25  *         16.07.2012 11:05:26
    26  * 
    27  */
    28 public class DijkstraSolver extends AbstractSolver {
    29 
    30 	protected Map<String, Set<Movement>>	loseMovs							= new HashMap<String, Set<Movement>>();
    31 	protected Map<String, Set<CellsLink>>	loseLinks							= new HashMap<String, Set<CellsLink>>();
    32 	protected Map<String, Set<Coordinate>>	attendedWalkingAroundCoordinates	= new HashMap<String, Set<Coordinate>>();
    33 	protected Map<String, Set<Coordinate>>	noWay								= new HashMap<String, Set<Coordinate>>();
    34 
    35 	public DijkstraSolver(Mine mine, SolverListener listener) {
    36 		super(mine, listener);
    37 	}
    38 
    39 	@Override
    40 	public void solve() {
    41 		while (true) {
    42 			Mine mine = null;
    43 			mine = initialMine.clone();
    44 			Game game = new Game(mine);
    45 
    46 			while (game.getState() == GameState.Game) {
    47 				Cell robotCell = mine.getRobotCell();
    48 				String map = mine.toText();
    49 				String mapWithoutRobot = mine.toTextWithoutRobot();
    50 				if (!loseMovs.containsKey(map)) {
    51 					loseMovs.put(map, new HashSet<Movement>());
    52 				}
    53 				if (!loseLinks.containsKey(map)) {
    54 					loseLinks.put(map, new HashSet<CellsLink>());
    55 				}
    56 				if (!noWay.containsKey(map)) {
    57 					noWay.put(map, new HashSet<Coordinate>());
    58 				}
    59 				if (!attendedWalkingAroundCoordinates.containsKey(mapWithoutRobot)) {
    60 					attendedWalkingAroundCoordinates.put(mapWithoutRobot, new HashSet<Coordinate>());
    61 				}
    62 				attendedWalkingAroundCoordinates.get(mapWithoutRobot).add(robotCell.getCoordinate());
    63 				Set<Cell> targets = new HashSet<Cell>();
    64 				boolean isFreeWay = false;
    65 				for (Cell cell : mine.getAdjacentCells(robotCell)) {
    66 					Movement mov = robotCell.getCoordinate().getNecessaryMovement(cell.getCoordinate());
    67 					isFreeWay |= !attendedWalkingAroundCoordinates.get(mapWithoutRobot).contains(cell.getCoordinate())
    68 							&& !loseMovs.get(map).contains(mov);
    69 				}
    70 				if (isFreeWay) {
    71 					targets.addAll(mine.findCells(CellContent.Lambda));
    72 					targets.addAll(mine.findCells(CellContent.HighOrderRock));
    73 					if (targets.size() == 0)
    74 						targets.addAll(mine.findCells(CellContent.OpenLambdaLift));
    75 					targets.removeAll(mine.getCells(noWay.get(map)));
    76 				} else {
    77 					targets.addAll(mine.findCells(CellContent.Empty));
    78 					targets.addAll(mine.findCells(CellContent.Earth));
    79 					targets.addAll(mine.findCells(CellContent.HuttonsRazor));
    80 					for (CellContent content : CellContent.getTrampolines()) {
    81 						targets.addAll(mine.findCells(content));
    82 					}
    83 					targets.removeAll(mine.getCells(attendedWalkingAroundCoordinates.get(mapWithoutRobot)));
    84 					targets.removeAll(mine.getCells(noWay.get(map)));
    85 					if (targets.size() == 0) {
    86 						game.move(Movement.ABORT);
    87 						continue;
    88 					}
    89 				}
    90 				Graph<Cell, CellsLink> graph = getDirectedGraph(mine);
    91 				DijkstraShortestPath<Cell, CellsLink> alg = new DijkstraShortestPath<Cell, CellsLink>(graph,
    92 						new CellsLinkTransformer<CellsLink, Double>());
    93 				Cell nextTarget = null;
    94 				List<CellsLink> routeToNextTarget = null;
    95 				double shortestDist = Double.MAX_VALUE;
    96 				for (Cell target : targets) {
    97 					List<CellsLink> route = null;
    98 					Number dist = null;
    99 					try {
   100 						route = alg.getPath(mine.getRobotCell(), target);
   101 						dist = alg.getDistance(mine.getRobotCell(), target);
   102 					} catch (IllegalArgumentException e) {
   103 						noWay.get(map).add(target.getCoordinate());
   104 						continue;
   105 					}
   106 					if (dist != null && route != null && route.size() > 0 && dist.doubleValue() < shortestDist) {
   107 						CellsLink firstLink = route.get(0);
   108 						Movement mov = firstLink.getSource().getCoordinate()
   109 								.getNecessaryMovement(firstLink.getTarget().getCoordinate());
   110 						if (!loseMovs.get(map).contains(mov)
   111 								&& !attendedWalkingAroundCoordinates.get(mapWithoutRobot).contains(
   112 										target.getCoordinate())) {
   113 							shortestDist = dist.doubleValue();
   114 							nextTarget = target;
   115 							routeToNextTarget = route;
   116 						}
   117 					}
   118 				}
   119 				if (nextTarget != null) {
   120 					for (CellsLink link : routeToNextTarget) {
   121 						Cell source = link.getSource();
   122 						Cell target = link.getTarget();
   123 						if (isSafeMovement(mine, source, target)) {
   124 							Movement mov = source.getCoordinate().getNecessaryMovement(target.getCoordinate());
   125 							GameState state = game.move(mov);
   126 							if (state == GameState.Lose || state == GameState.Abort) {
   127 								loseMovs.get(map).add(mov);
   128 								loseLinks.get(map).add(link);
   129 							}
   130 						}
   131 						break;
   132 					}
   133 				} else {
   134 					// Walking around
   135 					for (Movement mov : Movement.values()) {
   136 						if (!loseMovs.get(map).contains(mov)) {
   137 							if (mov == Movement.RAZOR && mine.getRazorsCount() > 0) {
   138 								boolean isRazorApplied = false;
   139 								for (Cell cell : mine.getNeighboringCells(robotCell)) {
   140 									isRazorApplied |= cell.getContent() == CellContent.WadlersBeard;
   141 								}
   142 								if (!isRazorApplied)
   143 									continue;
   144 							}
   145 							Cell movCell = null;
   146 							for (Cell cell : mine.getAdjacentCells(robotCell)) {
   147 								if (robotCell.getCoordinate().getNecessaryMovement(cell.getCoordinate()) == mov) {
   148 									if (!attendedWalkingAroundCoordinates.get(mapWithoutRobot).contains(
   149 											cell.getCoordinate())) {
   150 										movCell = cell;
   151 										break;
   152 									}
   153 								}
   154 
   155 							}
   156 							if (mov == Movement.WAIT
   157 									|| mov == Movement.RAZOR
   158 									|| movCell != null
   159 									&& !attendedWalkingAroundCoordinates.get(mapWithoutRobot).contains(
   160 											movCell.getCoordinate())) {
   161 								GameState state = game.move(mov);
   162 								if (movCell != null && mapWithoutRobot.equals(mine.toTextWithoutRobot()))
   163 									attendedWalkingAroundCoordinates.get(mapWithoutRobot).add(movCell.getCoordinate());
   164 								if (state == GameState.Game && map.equals(mine.toText())) {
   165 									loseMovs.get(map).add(mov);
   166 								}
   167 								break;
   168 							}
   169 						}
   170 					}
   171 				}
   172 			}
   173 			addNewRoute(game);
   174 			attemptsCount++;
   175 		}
   176 	}
   177 
   178 	protected boolean isSafeMovement(Mine mine, Cell source, Cell target) {
   179 		if (source == null || target == null)
   180 			return false;
   181 		if (source.getContent().getTrampolineTarget() == target.getContent())
   182 			return true;
   183 		Cell upCell = mine.getCell(target.getCoordinate().up());
   184 		if (upCell == null)
   185 			return true;
   186 		Cell upUpCell = mine.getCell(target.getCoordinate().up().up());
   187 		Cell upUpLeftCell = mine.getCell(target.getCoordinate().up().up().left());
   188 		Cell upUpRightCell = mine.getCell(target.getCoordinate().up().up().right());
   189 		if (upCell.getContent() == CellContent.Empty
   190 				&& (upUpCell != null
   191 						&& (upUpCell.getContent() == CellContent.Rock || upUpCell.getContent() == CellContent.HighOrderRock)
   192 						|| upUpLeftCell != null
   193 						&& (upUpLeftCell.getContent() == CellContent.Rock || upUpLeftCell.getContent() == CellContent.HighOrderRock) || upUpRightCell != null
   194 						&& (upUpRightCell.getContent() == CellContent.Rock || upUpRightCell.getContent() == CellContent.HighOrderRock))) {
   195 			return false;
   196 		}
   197 		return true;
   198 	}
   199 
   200 	protected Graph<Cell, CellsLink> getDirectedGraph(Mine mine) {
   201 		Graph<Cell, CellsLink> graph = new DirectedSparseGraph<Cell, CellsLink>();
   202 		for (CellsLink link : getCellLinks(mine)) {
   203 			graph.addEdge(link, link.getSource(), link.getTarget());
   204 		}
   205 		return graph;
   206 	}
   207 
   208 	protected List<CellsLink> getCellLinks(Mine mine) {
   209 		List<CellsLink> links = new ArrayList<CellsLink>();
   210 		Cell robotCell = mine.getRobotCell();
   211 		findAllCellLinks(mine, robotCell, links, new HashSet<Cell>());
   212 		return links;
   213 	}
   214 
   215 	protected void findAllCellLinks(Mine mine, Cell cell, List<CellsLink> links, Set<Cell> processedCells) {
   216 		if (processedCells.contains(cell))
   217 			return;
   218 		else
   219 			processedCells.add(cell);
   220 		String map = mine.toText();
   221 		for (Cell neighboringCell : mine.getAdjacentCells(cell)) {
   222 			if (neighboringCell == null)
   223 				continue;
   224 			CellContent neighboringContent = neighboringCell.getContent();
   225 			if (neighboringContent == CellContent.Earth || neighboringContent == CellContent.Empty
   226 					|| neighboringContent == CellContent.HuttonsRazor || neighboringContent == CellContent.Lambda
   227 					|| neighboringContent == CellContent.OpenLambdaLift) {
   228 				if (isSafeMovement(mine, cell, neighboringCell)) {
   229 					CellsLink link = new CellsLink(mine, cell, neighboringCell);
   230 					if (!loseLinks.get(map).contains(link)) {
   231 						links.add(link);
   232 						findAllCellLinks(mine, neighboringCell, links, processedCells);
   233 					}
   234 				}
   235 			} else if (!CellContent.getTargets().contains(cell.getContent())
   236 					&& CellContent.getTargets().contains(neighboringContent)) {
   237 				findAllCellLinks(mine, neighboringCell, links, processedCells);
   238 			}
   239 		}
   240 		if (CellContent.getTrampolines().contains(cell.getContent())) {
   241 			for (Cell target : mine.findCells(cell.getContent().getTrampolineTarget())) {
   242 				if (target == null)
   243 					continue;
   244 				if (isSafeMovement(mine, cell, target)) {
   245 					CellsLink link = new CellsLink(mine, cell, target);
   246 					if (!loseLinks.get(map).contains(link)) {
   247 						links.add(link);
   248 						findAllCellLinks(mine, target, links, processedCells);
   249 					}
   250 				}
   251 			}
   252 		}
   253 	}
   254 }