问题:具有约束的多点之间的网格中的最短路径
Problem: Shortest path in a grid between multiple point with a constraint
问题描述:
我正在尝试解决 Internet 上的问题,但我无法通过所有测试用例,嗯,因为我的逻辑有缺陷且不正确。缺陷:我假设从最近的 'F' 点开始,在任何情况下都会让我到达最短路径。
我想到的:
- 将其转化为图形问题,并以此为基础进行求解。 > 不认为这会因为限制而起作用吗?
- 尝试获得所有可能的解决方案组合 > 不缩放,如果存在 !8 组合。
#include <iostream>
#include <utility>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define N 4
#define M 4
int SearchingChallenge(string strArr[], int arrLength) {
int n = arrLength, m = n, steps = 0, food = 0;
// initial position of charlie
int init_j = 0;
int init_i = 0;
queue<pair<int,int>> q;
// directions
vector<int> offsets = {0,-1,0,1,0};
vector<pair<int,int>> food_nodes;
//store visited nodes, no need for extra work to be done.
int visited_nodes[4][4] = {{0}};
// get number of food pieces
for(int i = 0; i < m; i++){
for(int j = 0; j < n ; j++){
if(strArr[i][j] == 'F')
{
food++;
}
if(strArr[i][j] == 'C')
{
strArr[i][j] = 'O';
food_nodes.push_back({i,j});
}
}
}
while(food_nodes.size()>0){
food_nodes.erase(food_nodes.begin());
int break_flag=0;
q.push(food_nodes[0]);
while(!q.empty()){
int size = q.size();
while(size-->0){
pair<int,int> p = q.front();
q.pop();
for(int k = 0; k < 4; k++){
int ii = p.first + offsets[k], jj = p.second + offsets[k+1];
/* if(ii == 0 && jj == 3)
printf("HI"); */
if(jj >= 0 && jj < 4 && ii < 4 && ii >=0){
if(strArr[ii][jj] == 'F'){
strArr[ii][jj] = 'O';
while(!q.empty())
q.pop();
break_flag=1;
food--;
food_nodes.push_back({ii,jj});
break;
}
if(strArr[ii][jj] == 'O')
q.push({ii,jj});
if(strArr[ii][jj] == 'H' && food == 0)
return ++steps;
}
}
if(break_flag==1)
break;
}
steps++;
if(break_flag==1)
break;
}
}
return 0;
}
int main(void) {
// keep this function call here
/* Note: In C++ you first have to initialize an array and set
it equal to the stdin to test your code with arrays. */
//passing testcase
//string A[4] = {"OOOO", "OOFF", "OCHO", "OFOO"};
//failing testcase
string A[4] = {"FOOF", "OCOO", "OOOH", "FOOO"}
int arrLength = sizeof(A) / sizeof(*A);
cout << SearchingChallenge(A, arrLength);
return 0;
}
感谢您的帮助。
您可以在具有 4x4x8 网格的地方编写 DP 解决方案。前两个轴表示 x 和 y 坐标。第三个代表您已经选择的食物的二进制编码。
网格中的每个单元格都存储了吃完指定食物后到达该单元格的最佳移动次数。因此,例如,grid[2][2][2] 是仅吃完第二块食物后到达单元格 (2,2) 的成本。
然后将第三个索引 0 处的起始单元格的值设置为 0,将所有其他单元格设置为 -1。您保留要传播的单元格列表(按最低成本排序),然后将起始单元格添加到其中。
然后你重复使用下一个单元格进行传播,将其删除并推送成本为 +1 的相邻单元格并更新食物消耗。一旦你到达目标单元格并消耗完所有食物,你就完成了。
这应该不会超过 4x4x8 次更新,并且优先级队列插入的顺序大致相同。 O(n log(n)) 其中 n 是 xy2^f。只要你的食物很少,这几乎是即时的。
我已经为上述问题编写了 javascript 解决方案..
function SearchingChallenge(strArr) {
// create coordinate array
const matrix = [
[0, 0], [0, 1], [0, 2], [0, 3],
[1, 0], [1, 1], [1, 2], [1, 3],
[2, 0], [2, 1], [2, 2], [2, 3],
[3, 0], [3, 1], [3, 2], [3, 3]
]
// flatten the strArr
const flattenArray = flatten(strArr)
// segreagate and map flattenArray with matrix to get coordinate of food,charlie and home
const segregatedCoordinates = flattenArray.reduce((obj, char, index) => {
if (char === 'F') obj['food'].push(matrix[index])
else if (char === 'C') obj['dog'] = matrix[index]
else if (char === 'H') obj['home'] = matrix[index]
return obj
}, { "food": [], dog: null, home: null })
// construct possible routes by permutating food coordinates
let possibleRoutes = permuate(segregatedCoordinates['food'])
// push dog and home in possibleRoutes at start and end positions
possibleRoutes = possibleRoutes.map((route) => {
return [segregatedCoordinates['dog'], ...route, segregatedCoordinates['home']]
})
// Calculate distances from every possible route
const distances = possibleRoutes.reduce((distances, route) => {
let moveLength = 0
for (let i = 0; i < route.length - 1; i++) {
let current = route[i], next = route[i + 1]
let xCoordinatePath = current[0] > next[0] ? (current[0] - next[0]) : (next[0] - current[0])
let yCoordinatePath = current[1] > next[1] ? (current[1] - next[1]) : (next[1] - current[1])
moveLength += xCoordinatePath + yCoordinatePath
}
distances.push(moveLength)
return distances
}, [])
return Math.min(...distances);
}
function permuate(arr) {
if (arr.length <= 2) return (arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr)
return arr.reduce((res, ele, index) => {
res = [...res, ...permuate([...arr.slice(0, index), ...arr.slice(index + 1)]).map(val => [ele, ...val])]
return res
}, [])
}
function flatten(inputtedArr) {
return inputtedArr.reduce((arr, row) => {
arr = [...arr, ...row]
return arr
}, [])
}
console.log(SearchingChallenge(['FOOF', 'OCOO', 'OOOH', 'FOOO']));
C++ 解决方案
我同时使用了 dfs 和 bfs 来解决这个问题
时间复杂度 - (4^(N×M))+NO_OF_FOODS×N×M
#include <bits/stdc++.h>
using namespace std;
//It is a dfs function it will find and store all the possible steps to eat all food in toHome map
void distAfterEatingAllFood(vector<vector<char>> &m, int countOfFood, int i, int j, int steps, map<pair<int,int>,int>&toHome){
if(i<0 || j<0 || i>=4 || j>=4 || m[i][j]=='*') return;
if(m[i][j]=='F') countOfFood--;
if(countOfFood==0){
if(!toHome.count({i,j}))
toHome[{i,j}] = steps;
else if(toHome[{i,j}]>steps)
toHome[{i,j}] = steps;
return;
}
char temp = m[i][j];
m[i][j] = '*';
distAfterEatingAllFood(m, countOfFood, i+1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i-1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j+1, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j-1, steps+1, toHome);
m[i][j] = temp;
return;
}
//It is a bfs function it will iterate over the toHome map and find the shortest distance between the last food position to home
int lastFoodToHome(vector<vector<char>> &m, int i, int j, int steps){
queue<pair<pair<int, int>,int>>q;
vector<vector<int>> vis(4, vector<int>(4, 0));
q.push({{i, j}, steps});
vis[i][j] = 1;
int dirX[] = {0, 1, 0, -1};
int dirY[] = {1, 0, -1, 0};
while (!q.empty())
{
int x = q.front().first.first;
int y = q.front().first.second;
int steps = q.front().second;
q.pop();
if (m[x][y] == 'H')
return steps;
for (int k = 0; k < 4; k++)
{
int ni = x + dirX[k];
int nj = y + dirY[k];
if (ni >= 0 && nj >= 0 && ni < 4 && nj < 4 && !vis[ni][nj])
{
if(m[ni][nj] == 'H') return steps + 1;
q.push({{ni, nj}, steps + 1});
vis[i][j] = 1;
}
}
}
return INT_MAX;
}
int main()
{
vector<vector<char>> m(4, vector<char>(4));
int countOfFood = 0, x, y;
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
cin >> m[i][j];
if (m[i][j] == 'C'){
x = i;
y = j;
}
if (m[i][j] == 'F')
countOfFood++;
}
}
map<pair<int,int>,int>toHome;
distAfterEatingAllFood(m, countOfFood, x, y, 0, toHome);
int ans = INT_MAX;
for(auto &i:toHome){
ans = min(ans, lastFoodToHome(m, i.first.first, i.first.second, i.second));
}
cout<<ans;
return 0;
}
问题描述:
我正在尝试解决 Internet 上的问题,但我无法通过所有测试用例,嗯,因为我的逻辑有缺陷且不正确。缺陷:我假设从最近的 'F' 点开始,在任何情况下都会让我到达最短路径。
我想到的:
- 将其转化为图形问题,并以此为基础进行求解。 > 不认为这会因为限制而起作用吗?
- 尝试获得所有可能的解决方案组合 > 不缩放,如果存在 !8 组合。
#include <iostream>
#include <utility>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define N 4
#define M 4
int SearchingChallenge(string strArr[], int arrLength) {
int n = arrLength, m = n, steps = 0, food = 0;
// initial position of charlie
int init_j = 0;
int init_i = 0;
queue<pair<int,int>> q;
// directions
vector<int> offsets = {0,-1,0,1,0};
vector<pair<int,int>> food_nodes;
//store visited nodes, no need for extra work to be done.
int visited_nodes[4][4] = {{0}};
// get number of food pieces
for(int i = 0; i < m; i++){
for(int j = 0; j < n ; j++){
if(strArr[i][j] == 'F')
{
food++;
}
if(strArr[i][j] == 'C')
{
strArr[i][j] = 'O';
food_nodes.push_back({i,j});
}
}
}
while(food_nodes.size()>0){
food_nodes.erase(food_nodes.begin());
int break_flag=0;
q.push(food_nodes[0]);
while(!q.empty()){
int size = q.size();
while(size-->0){
pair<int,int> p = q.front();
q.pop();
for(int k = 0; k < 4; k++){
int ii = p.first + offsets[k], jj = p.second + offsets[k+1];
/* if(ii == 0 && jj == 3)
printf("HI"); */
if(jj >= 0 && jj < 4 && ii < 4 && ii >=0){
if(strArr[ii][jj] == 'F'){
strArr[ii][jj] = 'O';
while(!q.empty())
q.pop();
break_flag=1;
food--;
food_nodes.push_back({ii,jj});
break;
}
if(strArr[ii][jj] == 'O')
q.push({ii,jj});
if(strArr[ii][jj] == 'H' && food == 0)
return ++steps;
}
}
if(break_flag==1)
break;
}
steps++;
if(break_flag==1)
break;
}
}
return 0;
}
int main(void) {
// keep this function call here
/* Note: In C++ you first have to initialize an array and set
it equal to the stdin to test your code with arrays. */
//passing testcase
//string A[4] = {"OOOO", "OOFF", "OCHO", "OFOO"};
//failing testcase
string A[4] = {"FOOF", "OCOO", "OOOH", "FOOO"}
int arrLength = sizeof(A) / sizeof(*A);
cout << SearchingChallenge(A, arrLength);
return 0;
}
感谢您的帮助。
您可以在具有 4x4x8 网格的地方编写 DP 解决方案。前两个轴表示 x 和 y 坐标。第三个代表您已经选择的食物的二进制编码。
网格中的每个单元格都存储了吃完指定食物后到达该单元格的最佳移动次数。因此,例如,grid[2][2][2] 是仅吃完第二块食物后到达单元格 (2,2) 的成本。
然后将第三个索引 0 处的起始单元格的值设置为 0,将所有其他单元格设置为 -1。您保留要传播的单元格列表(按最低成本排序),然后将起始单元格添加到其中。
然后你重复使用下一个单元格进行传播,将其删除并推送成本为 +1 的相邻单元格并更新食物消耗。一旦你到达目标单元格并消耗完所有食物,你就完成了。
这应该不会超过 4x4x8 次更新,并且优先级队列插入的顺序大致相同。 O(n log(n)) 其中 n 是 xy2^f。只要你的食物很少,这几乎是即时的。
我已经为上述问题编写了 javascript 解决方案..
function SearchingChallenge(strArr) {
// create coordinate array
const matrix = [
[0, 0], [0, 1], [0, 2], [0, 3],
[1, 0], [1, 1], [1, 2], [1, 3],
[2, 0], [2, 1], [2, 2], [2, 3],
[3, 0], [3, 1], [3, 2], [3, 3]
]
// flatten the strArr
const flattenArray = flatten(strArr)
// segreagate and map flattenArray with matrix to get coordinate of food,charlie and home
const segregatedCoordinates = flattenArray.reduce((obj, char, index) => {
if (char === 'F') obj['food'].push(matrix[index])
else if (char === 'C') obj['dog'] = matrix[index]
else if (char === 'H') obj['home'] = matrix[index]
return obj
}, { "food": [], dog: null, home: null })
// construct possible routes by permutating food coordinates
let possibleRoutes = permuate(segregatedCoordinates['food'])
// push dog and home in possibleRoutes at start and end positions
possibleRoutes = possibleRoutes.map((route) => {
return [segregatedCoordinates['dog'], ...route, segregatedCoordinates['home']]
})
// Calculate distances from every possible route
const distances = possibleRoutes.reduce((distances, route) => {
let moveLength = 0
for (let i = 0; i < route.length - 1; i++) {
let current = route[i], next = route[i + 1]
let xCoordinatePath = current[0] > next[0] ? (current[0] - next[0]) : (next[0] - current[0])
let yCoordinatePath = current[1] > next[1] ? (current[1] - next[1]) : (next[1] - current[1])
moveLength += xCoordinatePath + yCoordinatePath
}
distances.push(moveLength)
return distances
}, [])
return Math.min(...distances);
}
function permuate(arr) {
if (arr.length <= 2) return (arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr)
return arr.reduce((res, ele, index) => {
res = [...res, ...permuate([...arr.slice(0, index), ...arr.slice(index + 1)]).map(val => [ele, ...val])]
return res
}, [])
}
function flatten(inputtedArr) {
return inputtedArr.reduce((arr, row) => {
arr = [...arr, ...row]
return arr
}, [])
}
console.log(SearchingChallenge(['FOOF', 'OCOO', 'OOOH', 'FOOO']));
C++ 解决方案
我同时使用了 dfs 和 bfs 来解决这个问题
时间复杂度 - (4^(N×M))+NO_OF_FOODS×N×M
#include <bits/stdc++.h>
using namespace std;
//It is a dfs function it will find and store all the possible steps to eat all food in toHome map
void distAfterEatingAllFood(vector<vector<char>> &m, int countOfFood, int i, int j, int steps, map<pair<int,int>,int>&toHome){
if(i<0 || j<0 || i>=4 || j>=4 || m[i][j]=='*') return;
if(m[i][j]=='F') countOfFood--;
if(countOfFood==0){
if(!toHome.count({i,j}))
toHome[{i,j}] = steps;
else if(toHome[{i,j}]>steps)
toHome[{i,j}] = steps;
return;
}
char temp = m[i][j];
m[i][j] = '*';
distAfterEatingAllFood(m, countOfFood, i+1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i-1, j, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j+1, steps+1, toHome);
distAfterEatingAllFood(m, countOfFood, i, j-1, steps+1, toHome);
m[i][j] = temp;
return;
}
//It is a bfs function it will iterate over the toHome map and find the shortest distance between the last food position to home
int lastFoodToHome(vector<vector<char>> &m, int i, int j, int steps){
queue<pair<pair<int, int>,int>>q;
vector<vector<int>> vis(4, vector<int>(4, 0));
q.push({{i, j}, steps});
vis[i][j] = 1;
int dirX[] = {0, 1, 0, -1};
int dirY[] = {1, 0, -1, 0};
while (!q.empty())
{
int x = q.front().first.first;
int y = q.front().first.second;
int steps = q.front().second;
q.pop();
if (m[x][y] == 'H')
return steps;
for (int k = 0; k < 4; k++)
{
int ni = x + dirX[k];
int nj = y + dirY[k];
if (ni >= 0 && nj >= 0 && ni < 4 && nj < 4 && !vis[ni][nj])
{
if(m[ni][nj] == 'H') return steps + 1;
q.push({{ni, nj}, steps + 1});
vis[i][j] = 1;
}
}
}
return INT_MAX;
}
int main()
{
vector<vector<char>> m(4, vector<char>(4));
int countOfFood = 0, x, y;
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
cin >> m[i][j];
if (m[i][j] == 'C'){
x = i;
y = j;
}
if (m[i][j] == 'F')
countOfFood++;
}
}
map<pair<int,int>,int>toHome;
distAfterEatingAllFood(m, countOfFood, x, y, 0, toHome);
int ans = INT_MAX;
for(auto &i:toHome){
ans = min(ans, lastFoodToHome(m, i.first.first, i.first.second, i.second));
}
cout<<ans;
return 0;
}