Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
舒服!一次性A了。附Java代码。BFS + DFSimport java.util.Scanner; public class CleaningRobot { static int M, N; static char map[][]; static int result; static int[] dirtyX; static int[] dirtyY; static int numOfDirty; static int[][] director = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; static int distance[][]; static boolean impossible; public static void main(String[] args) { Scanner in = new Scanner(System.in); while (true) { N = in.nextInt(); M = in.nextInt(); if (M == 0 && N == 0) break; result = 0xfffff; impossible = false; dirtyX = new int[11]; dirtyY = new int[11]; numOfDirty = 0; map = new char[M][N]; for (int i = 0; i < M; i++) { String s = in.next(); for (int j = 0; j < N; j++) { map[i][j] = s.charAt(j); if (map[i][j] == '*') { numOfDirty++; dirtyX[numOfDirty] = i; dirtyY[numOfDirty] = j; } else if (map[i][j] == 'o') { dirtyX[0] = i; dirtyY[0] = j; } } } distance = new int[numOfDirty+1][numOfDirty+1]; for(int i = 0; i < numOfDirty+1; i++){ if(impossible) break; for(int j = i + 1; j < numOfDirty+1; j++){ if(impossible) break; BFS(i, j); } } if(impossible){ System.out.println(-1); continue; } DFS(0, 0, 0, new boolean[numOfDirty + 1]); System.out.println(result); } in.close(); } static void BFS(int i, int j){ int step = 0; boolean visited[][] = new boolean[M][N]; int numInQue = 1; int queX[] = new int[M * N]; int queY[] = new int[M * N]; queX[0] = dirtyX[i]; queY[0] = dirtyY[i]; int destiX = dirtyX[j]; int destiY = dirtyY[j]; boolean flag = false; while(numInQue != 0){ step++; int queXTEMP[] = new int[M * N]; int queYTEMP[] = new int[M * N]; int numInQueTemp = 0; for(int k = 0; k < numInQue; k++){ for(int d = 0; d < 4; d++){ int x = queX[k] + director[d][0]; int y = queY[k] + director[d][1]; if(x == destiX && y == destiY) flag = true; if(x >= 0 && x < M && y >= 0 && y < N && !visited[x][y] && map[x][y] != 'x'){ queXTEMP[numInQueTemp] = x; queYTEMP[numInQueTemp] = y; numInQueTemp++; visited[x][y] = true; } } } if(flag) break; numInQue = numInQueTemp; queX = queXTEMP; queY = queYTEMP; } if(!flag){ impossible = true; return; } distance[i][j] = step; distance[j][i] = step; } static void DFS(int step, int next, int preDis, boolean visited[]){ if(preDis > result) return; if(step == numOfDirty){ result = preDis; return; } for(int i = 1; i < numOfDirty + 1; i++){ if(visited[i]) continue; visited[i] = true; DFS(step + 1, i, preDis + distance[next][i], visited); visited[i] = false; } } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator