对于宫格地图寻最短路径的一个广度搜索算法
2016-02-18 16:50 taixuyingcai 阅读(404) 评论(0) 编辑 收藏 举报1 import java.util.ArrayDeque; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map.Entry; 6 import java.util.Queue; 7 8 public class TestPath { 9 10 public static void main(String[] args) { 11 int arr[][] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 12 { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, 13 { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, 14 { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, 15 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 16 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 17 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 18 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 19 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 20 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; 21 Queue<String> list = new ArrayDeque<>(100); 22 arr[0][0] = 1; 23 list.add("0,0,0"); 24 HashMap<Integer, ArrayList<String>> map = new HashMap<>(); 25 int dis = 1; 26 Iterator<String> ite = list.iterator(); 27 28 while (ite.hasNext()) { 29 String[] tm = ite.next().split(","); 30 int i = Integer.parseInt(tm[0]); 31 int j = Integer.parseInt(tm[1]); 32 if (i + 1 > 0 && i + 1 < 10 && arr[i + 1][j] != 1) { 33 dis = Integer.parseInt(tm[2]) + 1; 34 String p = (i + 1) + "," + j + "," + dis; 35 arr[i + 1][j] = 1; 36 list.add(p); 37 if (map.get(dis) == null) { 38 map.put(dis, new ArrayList<String>()); 39 } 40 map.get(dis).add(p); 41 } 42 if (i - 1 > 0 && i - 1 < 10 && arr[i - 1][j] != 1) { 43 dis = Integer.parseInt(tm[2]) + 1; 44 String p = (i + 1) + "," + j + "," + dis; 45 arr[i + 1][j] = 1; 46 list.add(p); 47 if (map.get(dis) == null) { 48 map.put(dis, new ArrayList<String>()); 49 } 50 map.get(dis).add(p); 51 } 52 if (j + 1 > 0 && j + 1 < 10 && arr[i][j + 1] != 1) { 53 dis = Integer.parseInt(tm[2]) + 1; 54 String p = i + "," + (j + 1) + "," + dis; 55 arr[i][j + 1] = 1; 56 list.add(p); 57 if (map.get(dis) == null) { 58 map.put(dis, new ArrayList<String>()); 59 } 60 map.get(dis).add(p); 61 } 62 if (j - 1 > 0 && j - 1 < 10 && arr[i][j - 1] != 1) { 63 dis = Integer.parseInt(tm[2]) + 1; 64 String p = i + "," + (j + 1) + "," + dis; 65 arr[i][j + 1] = 1; 66 list.add(p); 67 if (map.get(dis) == null) { 68 map.put(dis, new ArrayList<String>()); 69 } 70 map.get(dis).add(p); 71 } 72 ite.remove(); 73 ite = list.iterator(); 74 } 75 for (int i = 0; i < map.get(3).size(); i++) { 76 System.out.println(map.get(3).get(i)); 77 } 78 for (Entry<Integer, ArrayList<String>> m: map.entrySet()) { 79 for (String str : m.getValue()) { 80 if (str.startsWith("2,4")) { 81 System.out.println(str); 82 } 83 } 84 } 85 } 86 87 }
记录了各个点到(0,0)点的距离,其中数组中值为1的点是不可通过的点。