Shopee物流會有很多箇中轉站。在選址的過程中,會選擇離用戶最近的地方建一個物流中轉站。
假設給你一個二維平面網格,每個格子是房子則爲1,或者是空地則爲0。找到一個空地修建一個物流中轉站,使得這個物流中轉站到所有的房子的距離之和最小。 能修建,則返回最小的距離和。如果無法修建,則返回 -1。
若範圍限制在100*100以內的網格,如何計算出最小的距離和?
當平面網格非常大的情況下,如何避免不必要的計算?
輸入描述:
4 0 1 1 0 1 1 0 1 0 0 1 0 0 0 0 0 先輸入方陣階數,然後逐行輸入房子和空地的數據,以空格分隔。
輸出描述:
8 能修建,則返回最小的距離和。如果無法修建,則返回 -1。
示例1
輸入
4 0 1 1 0 1 1 0 1 0 0 1 0 0 0 0 0
輸出
8
分析
通過暴力求解,建立輔助數組result,計算每一個空地到房子的距離之和,然後通過比較大小的方式解決問題。
遍歷原數組,如果爲0則將假設該地爲中間站,計算中轉站到後面房子的距離(橫縱座標絕對值)。
那麼中轉站到前面房子的值呢,可以通過遍歷到1的時候,累加1到後面0(中轉站)的距離值到result當中,這樣就解決了該問題,或者是通過數組的逆序遍歷計算距離值也可以行。
package com.ep.shop.test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [][] q = new int[n][n];
int [][] result = new int[n][n];
for(int i=0; i < n; i++){
for(int j=0; j < n; j++){
q[i][j] = sc.nextInt();
result[i][j] = 0;
}
}
sc.close();
for(int i=0; i < n; i++){
for(int j=0; j < n; j++){
if(q[i][j] == 0){
findOne(q, result, i, j, n); //碰到0就往後面找1
}else{
result[i][j] = Integer.MAX_VALUE;
findZero(q, result,i, j, n); //否則就找0
}
}
}
int minResult = Integer.MAX_VALUE;
for(int i=0; i < n; i++){
for(int j=0; j < n; j++){
if(result[i][j] < minResult){
minResult = result[i][j];
}
}
}
minResult = minResult == Integer.MAX_VALUE ? -1: minResult;
System.out.println(minResult);
for(int i=0; i < n; i++){
for(int j=0; j < n; j++){
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
private static void findZero(int[][] q, int[][] result, int x, int y, int n) {
int j = y;
for(int i=x; i < n; i++){
for(; j < n; j++){
if(q[i][j] == 0){
result[i][j] += (Math.abs(i - x) + Math.abs(j - y)); //把距離分散到碰到的0上面
}
}
j = 0;
}
}
private static void findOne(int[][] q, int[][] result, int x, int y, int n) {
int j = y;
for(int i=x; i < n; i++){
for(; j < n; j++){
if(q[i][j] == 1){
result[x][y] += (Math.abs(i - x) + Math.abs(j - y)); //把距離累加到 result[x][y]上
}
}
j = 0;
}
}
}