[CareerCup] Guards in a museum 博物馆的警卫

A museum was represented by a square matrix that was filled with O, G, and W where O represented open space, G represented guards, and W represented walls. Write a function that accepts the square matrix and returns another square matrix where all of the O's in the matrix are replaced with the number of how many spaces they are from a guard, without being able to go through any walls.

思路:

用BFS,先找到第一个guard,然后做bfs,找到所有的guard路径中最短的,其中如果遇到墙或者路径长度大于最小的路径就可以break返回了。循环查找,直到结束。

Java:

class Solution {
	class Position {
		int i;
		int j;
		int distance;

		public Position(int i, int j, int dist) {
			this.i = i;
			this.j = j;
			this.distance = dist;
		}

		public Position() {
			this.i = -1;
			this.j = -1;
			this.distance = -1;
		}
	}

	public static void main(String[] args) {
		char[][] matrix = { { 'o', 'o', 'o', 'g', 'o' }, { 'o', 'o', 'w', 'o', 'o' }, { 'o', 'g', 'o', 'o', 'w' },
				{ 'o', 'w', 'g', 'o', 'o' }, { 'w', 'o', 'o', 'o', 'g' } };
		Solution sol = new Solution();

		int[][] result = sol.findDistance(matrix);

		if (result == null) {
			System.out.println("Invalid input Matrix");
		}

		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[0].length; j++) {
				System.out.print(result[i][j] + " ");
			}
			System.out.println();
		}

	}

	public int[][] findDistance(char[][] matrix) {
		if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
			return null;
		}
		int[][] result = new int[matrix.length][matrix[0].length];

		Queue<Position> q = new LinkedList<Position>();
		// finding Guards location and adding into queue
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[0].length; j++) {
				result[i][j] = -1;
				if (matrix[i][j] == 'g') {
					q.offer(new Position(i, j, 0));
					result[i][j] = 0;
				}
			}
		}

		while (!q.isEmpty()) {
			Position p = q.poll();
			// result[p.i][p.j] = p.distance;
			updateNeighbors(p, matrix, q, result);
		}
		return result;
	}

	public void updateNeighbors(Position p, char[][] matrix, Queue<Position> q, int[][] result) {
		int[][] indexArray = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };

		for (int[] index : indexArray) {
			if (isValid(p.i + index[0], p.j + index[1], matrix, result)) {
				result[p.i + index[0]][p.j + index[1]] = p.distance + 1;
				q.offer(new Position(p.i + index[0], p.j + index[1], p.distance + 1));
			}
		}
	}

	public boolean isValid(int i, int j, char[][] matrix, int[][] result) {
		if ((i < 0 || i > matrix.length - 1) || (j < 0 || j > matrix[0].length - 1) || matrix[i][j] == 'w'
				|| matrix[i][j] == 'g' || result[i][j] != -1) {
			return false;
		}
		return true;
	}
}

  

 

posted @ 2018-03-02 02:41  轻风舞动  阅读(337)  评论(0编辑  收藏  举报