java面试题(1)
来源:互联网 发布:空间日志转载软件 编辑:程序博客网 时间:2024/05/22 07:57
原题:
// You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:// Each 0 marks an empty land which you can pass by freely.// Each 1 marks a building which you cannot pass through.// Each 2 marks an obstacle which you cannot pass through.// For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):// 1 - 0 - 2 - 0 - 1// | | | | |// 0 - 0 - 0 - 0 - 0// | | | | |// 0 - 0 - 1 - 0 - 0// The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.// Note:// There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
答案:
public class Solution { public int shortestDistance(int[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) return -1; final int[] shift = {0, 1, 0, -1, 0}; int rows = grid.length; int columns = grid[0].length; int[][] distance = new int[rows][columns]; int[][] reach = new int[rows][columns]; int numberOfBuildings = 0; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 1) { numberOfBuildings++; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(new int[] {i, j}); boolean[][] visited = new boolean[rows][columns]; int relativeDistance = 1; while(!queue.isEmpty()) { int qSize = queue.size(); for(int q = 0; q < qSize; q++) { int[] current = queue.poll(); for(int k = 0; k < 4; k++) { int nextRow = current[0] + shift[k]; int nextColumn = current[1] + shift[k + 1]; if(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && grid[nextRow][nextColumn] == 0 && !visited[nextRow][nextColumn]) { distance[nextRow][nextColumn] += relativeDistance; reach[nextRow][nextColumn]++; visited[nextRow][nextColumn] = true; queue.offer(new int[] {nextRow, nextColumn}); } } } relativeDistance++; } } } } int shortest = Integer.MAX_VALUE; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 0 && reach[i][j] == numberOfBuildings) { shortest = Math.min(shortest, distance[i][j]); } } } return shortest == Integer.MAX_VALUE ? -1 : shortest; }}
阅读全文
0 0
- java面试题1
- JAVA面试题-1
- java面试题1
- java面试题1
- JAVa面试题1
- java面试题1
- java面试题1
- java面试题1
- java面试题1
- java面试题1
- java面试题1
- java面试题1
- java面试题1
- Java面试题1
- JAVA面试题1
- JAVA面试题【1】
- Java面试题1
- java面试题1
- RadioGroup与FrameLayout配合时,需要点击RadioButtion改变颜色,可以改变图片
- 经典ARP协议讲解,一定要看
- http://hxraid.iteye.com/blog/504293
- 用VS 编写 Python C扩展
- 基于WiFi ESP8266 TCP UDP网络和SHT20的温湿度变送器方案设计
- java面试题(1)
- Optimization Method -- Gradient Descent with Momentum Gradient Descent (转)
- Business Intelligence
- 什么是hasLayout,更好的理解CSS
- RxJava操作符之转换操作符(四)
- 小圆点自动轮播
- java面试题(2)
- java面试题(3)
- 数据结构