Transcribing ASCII maze into graph
我有一个迷宫,如下所示:
1 2 3 4 5 6 7 8 9 10 | XXXOOOOX OXXXOXOE OXXOOXXO OSXOXXXO XOOOXOOO //X = wall //O = path //S = startpoint //E = endpoint |
我想把它转录成一个图(邻接矩阵),但我不确定我是否要这样做。邻接矩阵是布尔列表,其中true表示可获取路径,false表示不可能的路径(例如迷宫中的
1 2 | X E || A B S O || C D |
号
对于上面的迷宫(1=真,0=假),相邻矩阵会在下面吗?
1 2 3 4 5 6 7 8 | A B C D A 0 0 0 0 B 0 0 0 1 C 0 0 0 1 D 0 1 1 0 //C connects to D (start) //D connects to B (end) |
这真的很令人困惑,我不知道如何将x,y(有时也是z)坐标映射到一个图上。
试试这个
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 | static void set(boolean[][] paths, int cols, int row0, int col0, int row1, int col1) { int index0 = row0 * cols + col0; int index1 = row1 * cols + col1; paths[index0][index1] = paths[index1][index0]= true; } static boolean[][] paths(String[] maze) { int rows = maze.length; int cols = maze[0].length(); boolean[][] paths = new boolean[rows * cols][rows * cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (maze[i].charAt(j) == 'X') continue; if (i + 1 < rows && maze[i + 1].charAt(j) != 'X') set(paths, cols, i, j, i + 1, j); if (j + 1 < cols && maze[i].charAt(j + 1) != 'X') set(paths, cols, i, j, i, j + 1); } } return paths; } public static void main(String[] args) { String[] maze = { "XXXOOOOX", "OXXXOXOE", "OXXOOXXO", "OSXOXXXO", "XOOOXOOO", }; boolean[][] paths = paths(maze); for (boolean[] row : paths) { for (boolean cell : row) System.out.print(cell ?"1" :"0"); System.out.println(); } } |