You are on page 1of 3

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

Queue;

/** * @author Mike Hoye * CSC 321 Spring '13 * P5 - ShortestPath * Solution.java * */ public class Solution { static String[][] grid; static int beginRow; static int beginCol; static int endRow; static int endCol; static int gridSize; public static ArrayList<String> solve(ArrayList<String> data){ ArrayList<String> answer = new ArrayList<String>(); gridSize = Integer.parseInt(data.get(0)); grid = new String[gridSize][gridSize]; search(data); answer.add(grid[endRow][endCol]); return(answer); }

public static void buildGrid(ArrayList<String> data){ String points[] = new String[2]; points = data.get(1).split(","); beginRow = Integer.parseInt(points[0]); beginCol = Integer.parseInt(points[1]); points = data.get(2).split(","); endRow = Integer.parseInt(points[0]);

endCol = Integer.parseInt(points[1]); if (data.size() > 3){ for(int k = 3; k < data.size(); k++){ points = data.get(k).split(","); int p1 = Integer.parseInt(points[0]); int p2 = Integer.parseInt(points[1]); grid[p1][p2] = "Bomb!"; } } for (int n = 0; n < grid[0].length; n++){ for (int j = 0 ; j < grid[1].length; j++){ if(grid[n][j] != "Bomb!"){ grid[n][j] = ""; } } } } public static void search(ArrayList<String> data){ buildGrid(data); Queue<String> queue = new LinkedList<String>(); String begin = "" + beginRow + "," + beginCol; String end = grid[endRow][endCol]; queue.add(begin); while(!queue.isEmpty() && end == ""){ String curSpot[] = queue.peek().split(","); int curRow = Integer.parseInt(curSpot[0]); int curCol = Integer.parseInt(curSpot[1]); queue.remove(); String parent = grid[curRow][curCol]; int left = curCol - 1; int right = curCol + 1; int up = curRow - 1; int down = curRow+ 1; if(up >= 0 && grid[up][curCol] == ""){

grid[up][curCol] = parent + "U"; String U = "" + up + "," + curCol; queue.add(U); } if(down < grid.length && grid[down][curCol] == ""){ grid[down][curCol] = parent + "D"; String D = "" + down + "," + curCol; queue.add(D); } if(left >= 0 && grid[curRow][left] == ""){ grid[curRow][left] = parent + "L"; String L = "" + curRow + "," + left; queue.add(L); } if(right < grid.length && grid[curRow][right] == ""){ grid[curRow][right] = parent + "R"; String R = "" + curRow + "," + right; queue.add(R); } } } }

You might also like