我试图解决以下问题,但无法开发算法或方法。我已经研究了几个小时,并尝试将问题映射到“最短路径”图形/矩阵问题或动态编程问题,但是它没有成功。
给定宽度为w的网格,h为高度。网格的每个单元代表一个潜在的建筑物,我们将在该网格中添加“n”个建筑物。目标是使所有地段中最远的地方尽可能接近建筑物。给定输入n(即要放置在该批次中的建筑物数量),确定建筑物放置以最小化距离建筑物最远的空地段的距离。运动受限于水平和垂直,即不需要对角线运动。
例如,w=4, h=4 and n=3
。最佳网格布置可在建筑物的两个单位距离内设置任何批次。这个案子的答案是2。
“0”表示最佳建筑物放置,并且在这种情况下,每个单元到最近建筑物的所有最短距离的最大值是“2”。
1 0 1 2
2 1 2 1
1 0 1 0
2 1 2 1
以上代表一种最佳解决方案,可以更像上述旋转的阵列作为示例。以上是最佳解决方案,因为在3个建筑物(n = 3)中,一个建筑物放置在索引(0,1)处,第二个建筑物放置在(2,1)处,第三个建筑物放置在(2,3)处。每次水平和/或垂直移动时,周围的水平和垂直距离显示为1和2,加1。请再次注意,不允许对角线移动:
1 ← 0 → 1 → 2
↓
2 ← 1 → 2 ← 1
↑ ↑
1 ← 0 → 1 ← 0
↓ ↓
2 ← 1 → 2 ← 1
其他例子:
例1)
w=3, h=3, n=2
必须最佳地放置两个建筑物(零)。这种情况的最佳方案之一是:
01
11
10
0 → 1
↓
1 1
↑
1 ← 0
Answer: 1
例如,在这种情况下,下面的计划不是最优的,因为它的最大最小距离为2而不是1.因此,即使0覆盖三个“1”,将0贪婪地放在索引(1,0)也不起作用“在这种情况下的位置而不是上述最佳方案中的两个位置。
1 → 2
↑
0 → 1
↓ ↑
1 ← 0
例2)
w=5, h=1, n=1
一个建筑物(零)必须最佳放置。最佳计划之一:
2 ← 1 ← 0 → 1 → 2
Answer: 2
上述场景中非最优计划的示例:
3 ← 2 ← 1 ← 0 → 1
应完成以下功能:
int findMinDist(int w, int h, int n)
{
}
约束:
1<=w,h
w*h <=28
1<=n<=5
n<=w*h
我无法编写任何代码,因为老实说,我无法推断出解决方案。
如果两个给定点是2d矩阵中的固定点,我可以找到两者之间的距离或最短距离。但是,在这种情况下,我不知道这两点会在哪里?可以存在许多最佳解决方案并且在每个地方放置0的组合并且找不到最远距离是不可行的并且是不可行的。我试图将它们放在最大量为1的位置(如中间或w / 2),但这似乎也不起作用。现有算法可以应用于此问题吗?
根据给定的约束条件,矩阵大小(w * h)不能超过28,这是一个相当小的数字。此外,n的最大可能值是5.由于对组合学知之甚少,我们知道在最坏的情况下有28C5方法从给定网格中选择5个批次。该图评估为98280,这是一个足够小的空间来搜索记忆。由于w * h的最大值是28,我们可以用一个整数位掩码表示整个网格,它与剩下要建立的建筑物数量一起构成我们DP的状态。为了计算最终状态的最远剩余批次,我们通过使用我们设置建筑物的所有点初始化队列来利用广度优先搜索(BFS)。共享相同的代码运行足够快https://ideone.com/ix1nh8
int W, H, N;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, -1, 1};
int calc(int i, int j) {
if(W <= H)
return i + W * j;
return H * i + j;
}
bool get(int bitmask, int i, int j) {
return (bitmask&(1<<calc(i,j)));
}
int bfs(int bitmask) {
int dist[W][H];
memset(dist, -1, sizeof dist);
int maxDist = 0;
queue<pair<int,int>> Q;
for(int i = 0; i < W; i++)
for(int j = 0; j < H; j++)
if(get(bitmask, i, j)) {
dist[i][j] = 0;
Q.push({i, j});
}
assert(Q.size() == N);
while(!Q.empty()) {
int x = Q.front().first;
int y = Q.front().second;
maxDist = max(maxDist, dist[x][y]);
Q.pop();
for(int d = 0; d < 4; d++) {
int newx = x + dx[d];
int newy = y + dy[d];
if(newx >= W || newy >= H || newx < 0 || newy < 0)
continue;
if(dist[newx][newy] == -1) {
dist[newx][newy] = dist[x][y] + 1;
Q.push({newx, newy});
}
}
}
return maxDist;
}
map<pair<int,int>, int> dp;
int solve(int bitmask, int left) {
if(left == 0) {
return bfs(bitmask);
}
if(dp.find({bitmask, left}) != dp.end()) {
return dp[{bitmask, left}];
}
int minDistance = INT_MAX;
for(int i = 0; i < W; i++)
for(int j = 0; j < H; j++)
if(!get(bitmask, i, j)) {
int val = solve((bitmask|(1<<calc(i, j))), left-1);
minDistance = min(minDistance, val);
}
return dp[{bitmask, left}] = minDistance;
}
没有位掩码的Java解决方案,需要通过将位置传递给递归调用来进行memoization
class MaximumShortestDist
{
static int[] dx = new int[]{1, -1, 0, 0};
static int[] dy = new int[]{0, 0, -1, 1};
public static void main(String[] args) {
System.out.println(findMinDist(14,2,5));
}
static int findMinDist(int w, int h, int n)
{
int[][] grid = new int[w][h];
for(int i=0;i<w;i++)
Arrays.fill(grid[i],-1);
return solve(n,w,h,0,0,grid);
}
static int bfs(int W, int H, int[][] grid) {
int[][] dist = new int[W][H];
for(int i=0;i<W;i++)
for(int j=0;j<H;j++)
dist[i][j] = grid[i][j];
int maxDist = 0;
Queue<Location> Q = new LinkedList<>();
for(int i = 0; i < W; i++)
for(int j = 0; j < H; j++)
if(dist[i][j] == 0){
Q.add(new Location(i,j));
}
while(!Q.isEmpty()) {
int x = Q.peek().first;
int y = Q.peek().second;
maxDist = Math.max(maxDist, dist[x][y]);
Q.poll();
for(int d = 0; d < 4; d++) {
int newx = x + dx[d];
int newy = y + dy[d];
if(newx >= W || newy >= H || newx < 0 || newy < 0)
continue;
if(dist[newx][newy] == -1) {
dist[newx][newy] = dist[x][y] + 1;
Q.add(new Location(newx, newy));
}
}
}
return maxDist;
}
static int solve(int left, int W, int H, int row, int col,int[][] grid) {
if(left == 0) {
return bfs(W,H,grid);
}
int r = row,c=col;
if(col >= H) {
r += col/H;
c = col%H;
}
int minDistance = Integer.MAX_VALUE;
for(int i=r;i<W;i++){
for(int j=c;j<H;j++) {
//Mark Building locations in the recursive call.
grid[i][j] = 0;
int val = solve(left-1, W, H,i,j+1,grid);
minDistance = Math.min(minDistance, val);
// Remove the building
grid[i][j] = -1;
}
}
return minDistance;
}
}
class Location {
int first;
int second;
Location(int x, int y) {
first = x;
second = y;
}
}
没有按位运算的Java代码。
import javafx.util.Pair;
import java.util.*;
class Office_N {
// W for width, H for height, N for no of offices to build
int W, H, N;
// dx and dy value together gives (x,y)
// which helps to move in 4 adjacent cells
// Right (1,0)
// Left (-1,0)
// Down (0,1)
// Up (0,-1)
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
Map<String, Integer> dp = new HashMap<>();
int[][] grid;
// Constructor will set the values and clear the hashmap.
public Office_N(int w, int h, int n) {
W = w;
H = h;
N = n;
dp.clear();
grid = new int[W][H];
for (int[] r : grid) {
Arrays.fill(r, 0);
}
}
// We convert the 2D array of W*H into 1D array in Row Order (if square matrix or Width is less),
// or Column Wise (if Height is less)
// BitMask holds the bits 0 empty spots, and 1 for where offices are present
// Left means how many offices are still left to be built
public int solve(int[][] grid, int left) {
// If no more offices are left to be built, get the maximum distance for this scenario
if (left == 0) {
return bfs(grid);
}
StringBuilder k = new StringBuilder();
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
if (grid[i][j] == 1) {
k.append(i + ":" + j + "::");
}
}
}
k.append("#" + left);
// if the current scenario along with offices left are already processed, return the result
String key = k.toString();
if (dp.containsKey(key)) {
return dp.get(key);
}
int[][] gridtemp = new int[W][H];
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
gridtemp[i][j] = grid[i][j];
}
}
// We are trying every possible scenario to build offices in the given grid
int minDist = Integer.MAX_VALUE;
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
// If no office present in (i,j)th location, put one office there and check the minimum distance for that scenario
if (gridtemp[i][j] == 0) {
gridtemp[i][j] = 1;
int val = solve(gridtemp, left - 1);
minDist = Math.min(minDist, val);
gridtemp[i][j] = 0;
}
}
}
// Store the min distance possible for the current scenario
dp.put(key, minDist);
return minDist;
}
// This function gives the maximum distance from all the empty spots to the offices for a given case of scenario
private int bfs(int[][] grid) {
// get a distance matrix with initial values as -1
int[][] dist = new int[W][H];
for (int[] row : dist)
Arrays.fill(row, -1);
int maxDist = 0;
// Queue for processing the cells in Bredth-First-Search order.
Queue<Pair<Integer, Integer>> Q = new LinkedList<>();
// if office is present at (i,j)th location, the distance is 0, and put the (i,j) pair in Queue
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
if (grid[i][j] == 1) {
dist[i][j] = 0;
Q.add(new Pair<>(i, j));
}
}
}
while (!Q.isEmpty()) {
Pair<Integer, Integer> kv = Q.poll();
int x = kv.getKey();
int y = kv.getValue();
// Get maximum distance for (i,j)th location
maxDist = Math.max(maxDist, dist[x][y]);
// Process all adjacent cells
for (int d = 0; d < dx.length; d++) {
int xNew = x + dx[d];
int yNew = y + dy[d];
// if the adjacent cell is within grid boundary, and is not yet processed,
// set the max dist of he adjacent cell 1 more than the (i,j)th cell
// add the adjacent cell to queue
if (xNew >= 0 && xNew < W && yNew >= 0 && yNew < H && dist[xNew][yNew] == -1) {
dist[xNew][yNew] = dist[x][y] + 1;
Q.add(new Pair<>(xNew, yNew));
}
}
}
return maxDist;
}
public static void main(String[] args) {
Office_N ofc = new Office_N(4, 4, 3);
int res = ofc.solve(ofc.grid, ofc.N);
System.out.println(res);
}
}
我尝试使用python解决这个问题。答案的核心在于我的阶梯函数,该函数在W x H网格中获得N个建筑物的所有可能位置,并将结果作为列表给出。列表中的每个位置都是W * i + H处的位置。这是2x2中的位置被视为0,1,2,3。
# generator function to give each building position
# in a W x H grid
def step(W, H, N):
dim = W * H
slots = [n for n in range(N)]
slots_temp = list(slots)
persist = list(slots)
last = [dim - n for n in slots]
last = last[::-1]
while slots != [0] * N:
yield slots
for i in range(len(slots)-1,-1,-1):
slots[i]+=1
if slots[i] >= last[i] :
slots[i] = 0
else:
while i < len(slots)-1:
slots[i+1] = slots[i] + 1
i+=1
break
# converts a ixj to a step
# assumes W <= H
def get_step(i, j, W , H):
return (i * W) + j
# does bfs from each building position
# and gets the maximum distance
def bfs(step,W,H):
dist = [[-1]*H for i in range(W)]
queue = []
dx = [1,-1,0,0]
dy = [0,0,1,-1]
for i in range(W):
for j in range(H):
step_val = get_step(i, j, W, H)
if step_val in step:
dist[i][j] = 0
queue.append((i,j))
max_val = 0
while len(queue) != 0:
i,j = queue.pop(0)
max_val = max(max_val, dist[i][j])
for _dx,_dy in zip(dx,dy):
new_i,new_j = i + _dx, j + _dy
if new_i < 0 or new_i >= W or new_j <0 or new_j >= H:
continue
if dist[new_i][new_j] == -1:
dist[new_i][new_j] = dist[i][j] + 1
queue.append((new_i,new_j))
return max_val
# calls each posible position of the building
# and computes the minimum distance of all
def main(W, H, N ):
min_val = float('inf')
if W > H:
W, H = H, W
s = step(W, H, N)
for slot in s:
b = bfs(slot, W, H)
min_val = min(min_val, b)
return min_val
main(4, 4, 2)