1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
|
class Main { static int maxLine = 6, maxRow = 5; static int[][] map = new int[maxLine][maxRow]; static int[][] mark = new int[maxLine][maxRow]; static int targetLine = 4, targetRow = 3; static int totalStep = -1; static int[][] nextDirection = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };
public static void main(String[] args) { map[1][3] = 1; map[3][3] = 1; map[4][2] = 1; map[5][4] = 1; bfs(1, 1); System.out.print(totalStep == -1 ? "\n没有到达" : "\n到达"); System.out.println("目标位置: " + targetLine + "行" + targetRow + "列,总步数:" + totalStep); }
public static void bfs(int startLine, int startRow) { mark[startLine][startRow] = 1; Node[] queue = new Node[maxLine * maxRow]; int head = 0, tail = 0; queue[tail] = new Node(startLine, startRow, 0, head); tail++; int nextLine, nextRow; while (head < tail) { for (int i = 0; i < 4; i++) { nextLine = queue[head].getLine() + nextDirection[i][0]; nextRow = queue[head].getRow() + nextDirection[i][1]; if (nextLine >= maxLine || nextRow >= maxRow || nextLine < 1 || nextRow < 1) { continue; } if (mark[nextLine][nextRow] != 1 && map[nextLine][nextRow] != 1) { queue[tail] = new Node(nextRow, nextLine, queue[head].getStep() + 1, head); tail++; mark[nextLine][nextRow] = 1; } if (nextLine == targetLine && nextRow == targetRow) { int index = tail - 1; totalStep = queue[index].getStep(); for (int j = 0; j <= totalStep; j++) { System.out.println("(" + queue[index].getLine() + "," + queue[index].getRow() + ")"); index = queue[index].getNodeIndex(); } return; } } head++; } totalStep = -1; }
private static class Node { int nodeIndex; int row, line, step;
Node(int line, int row) { this.line = line; this.row = row; }
Node(int row, int line, int step, int nodeIndex) { this.row = row; this.line = line; this.step = step; this.nodeIndex = nodeIndex; }
public int getNodeIndex() { return nodeIndex; }
public int getRow() { return row; }
public int getLine() { return line; }
public int getStep() { return step; } } }
|