Find minimal wire connectionEasy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingRecursively Generating Binary Strings in Java using ArrayListefficient way to find set membershipChecking for similar numbers in the 2D array?Low-complexity computation of all binary vectors of length n, sorted by weightGiven a set and a pairwise xor set, find the second set?What is the most efficient way to generate subsets?Converting a number from decimal to binaryStoring all possible sequences of a binary string, JavaHow to generate every possible combination of elements in array between range

Using SPID in DB Tables (instead of Table Variable)

Why won't some unicode characters print to my terminal?

How slow can a car engine run?

What are the basics of commands in Minecraft Java Edition?

is 1hr 15 minutes enough time to change terminals at Manila?

Is it legal for a supermarket to refuse to sell an adult beer if an adult with them doesn’t have their ID?

Was Apollo 13 radio blackout on reentry longer than expected?

How did Jayne know when to shoot?

Demographic consequences of closed loop reincarnation

Is the Münchhausen trilemma really a trilemma?

Naming your baby - does the name influence the child?

Are there any restrictions on how amendment should be related to original law in US Senate?

Cauchy reals and Dedekind reals satisfy "the same mathematical theorems"

Who determines when road center lines are solid or dashed?

Practical example in using (homotopy) type theory

Is it ethical for a company to ask its employees to move furniture on a weekend?

When designing an adventure, how can I ensure a continuous player experience in a setting that's likely to favor TPKs?

Why do space operations use "nominal" to mean "working correctly"?

A scene of Jimmy diversity

Is it rude to refer to janitors as 'floor people'?

How to find location on Cambridge-Mildenhall railway that still has tracks/rails?

How to belay quickly ascending top-rope climbers?

Is Error correction and detection can be done with out adding extra bits?

How to stay a up-to-date researcher in ML/RL community?



Find minimal wire connection


Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingRecursively Generating Binary Strings in Java using ArrayListefficient way to find set membershipChecking for similar numbers in the 2D array?Low-complexity computation of all binary vectors of length n, sorted by weightGiven a set and a pairwise xor set, find the second set?What is the most efficient way to generate subsets?Converting a number from decimal to binaryStoring all possible sequences of a binary string, JavaHow to generate every possible combination of elements in array between range






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















The problem



You are given a board of size a by a. There're n components on the board, which have to be connected to the edges of the board with minimal length of wires possible.

Wires are straight and can't overlap.



Find the algorithm to do connect the components to the edges with these constraints.



Contstraints are:



time: 1s

space: infinity

1 <= a <= 30

1 <= n <= 38



Example:




Input:
4
3
2 1
2 3
3 3

Output:
5
DOWN
UP
UP


enter image description here




What I've already tried



I found a kind of recursion, let me show the idea with data provided above.



I have a n-bit mask, where 1 on i-th position represents, that we take this component into account, while 0 not.



When I start recursion I have n ones:




111
/ |
/ |
011 101 110
/ / /
001 010 001 100 010 100


When I came to the lowest level, I have exactly one 1. I find optimal solution (shortest way) for this simple problem and then I just use it for further computations.



However, I have a problem, that this optimal solution may lead to overlapping.










share|improve this question
























  • Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

    – Yonlif
    Mar 26 at 11:41












  • We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

    – Влад Казимиров
    Mar 26 at 12:01












  • This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

    – Влад Казимиров
    Mar 26 at 12:04











  • Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

    – Yonlif
    Mar 26 at 12:43











  • Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

    – גלעד ברקן
    Mar 26 at 13:11


















6















The problem



You are given a board of size a by a. There're n components on the board, which have to be connected to the edges of the board with minimal length of wires possible.

Wires are straight and can't overlap.



Find the algorithm to do connect the components to the edges with these constraints.



Contstraints are:



time: 1s

space: infinity

1 <= a <= 30

1 <= n <= 38



Example:




Input:
4
3
2 1
2 3
3 3

Output:
5
DOWN
UP
UP


enter image description here




What I've already tried



I found a kind of recursion, let me show the idea with data provided above.



I have a n-bit mask, where 1 on i-th position represents, that we take this component into account, while 0 not.



When I start recursion I have n ones:




111
/ |
/ |
011 101 110
/ / /
001 010 001 100 010 100


When I came to the lowest level, I have exactly one 1. I find optimal solution (shortest way) for this simple problem and then I just use it for further computations.



However, I have a problem, that this optimal solution may lead to overlapping.










share|improve this question
























  • Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

    – Yonlif
    Mar 26 at 11:41












  • We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

    – Влад Казимиров
    Mar 26 at 12:01












  • This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

    – Влад Казимиров
    Mar 26 at 12:04











  • Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

    – Yonlif
    Mar 26 at 12:43











  • Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

    – גלעד ברקן
    Mar 26 at 13:11














6












6








6


2






The problem



You are given a board of size a by a. There're n components on the board, which have to be connected to the edges of the board with minimal length of wires possible.

Wires are straight and can't overlap.



Find the algorithm to do connect the components to the edges with these constraints.



Contstraints are:



time: 1s

space: infinity

1 <= a <= 30

1 <= n <= 38



Example:




Input:
4
3
2 1
2 3
3 3

Output:
5
DOWN
UP
UP


enter image description here




What I've already tried



I found a kind of recursion, let me show the idea with data provided above.



I have a n-bit mask, where 1 on i-th position represents, that we take this component into account, while 0 not.



When I start recursion I have n ones:




111
/ |
/ |
011 101 110
/ / /
001 010 001 100 010 100


When I came to the lowest level, I have exactly one 1. I find optimal solution (shortest way) for this simple problem and then I just use it for further computations.



However, I have a problem, that this optimal solution may lead to overlapping.










share|improve this question
















The problem



You are given a board of size a by a. There're n components on the board, which have to be connected to the edges of the board with minimal length of wires possible.

Wires are straight and can't overlap.



Find the algorithm to do connect the components to the edges with these constraints.



Contstraints are:



time: 1s

space: infinity

1 <= a <= 30

1 <= n <= 38



Example:




Input:
4
3
2 1
2 3
3 3

Output:
5
DOWN
UP
UP


enter image description here




What I've already tried



I found a kind of recursion, let me show the idea with data provided above.



I have a n-bit mask, where 1 on i-th position represents, that we take this component into account, while 0 not.



When I start recursion I have n ones:




111
/ |
/ |
011 101 110
/ / /
001 010 001 100 010 100


When I came to the lowest level, I have exactly one 1. I find optimal solution (shortest way) for this simple problem and then I just use it for further computations.



However, I have a problem, that this optimal solution may lead to overlapping.







algorithm dynamic-programming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 11:10









Eric Wang

9,4687 gold badges75 silver badges111 bronze badges




9,4687 gold badges75 silver badges111 bronze badges










asked Mar 26 at 9:26









Влад КазимировВлад Казимиров

535 bronze badges




535 bronze badges












  • Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

    – Yonlif
    Mar 26 at 11:41












  • We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

    – Влад Казимиров
    Mar 26 at 12:01












  • This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

    – Влад Казимиров
    Mar 26 at 12:04











  • Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

    – Yonlif
    Mar 26 at 12:43











  • Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

    – גלעד ברקן
    Mar 26 at 13:11


















  • Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

    – Yonlif
    Mar 26 at 11:41












  • We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

    – Влад Казимиров
    Mar 26 at 12:01












  • This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

    – Влад Казимиров
    Mar 26 at 12:04











  • Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

    – Yonlif
    Mar 26 at 12:43











  • Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

    – גלעד ברקן
    Mar 26 at 13:11

















Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

– Yonlif
Mar 26 at 11:41






Can you please explain the input and output format? (What is that 5). Are you sure that there will always be solution? How this recursion tree tells you the solution exactly?

– Yonlif
Mar 26 at 11:41














We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

– Влад Казимиров
Mar 26 at 12:01






We receive a, which is the size of the square board, in the first line. Then we get n, which is the amount of components. After that we input n lines of coordinates of the contacts on the board. The output means the following: 5 - minimal total length of the wires possible And then the direction of wire going for i-th component. Yes, there could be a situation, when there will be no solution, but the input is guaranteed to be correct and solvable.

– Влад Казимиров
Mar 26 at 12:01














This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

– Влад Казимиров
Mar 26 at 12:04





This recursion tree represents the states of my dp. 001 means, that I ignore components #1 and #2 and find the minimal possible solution just for the component #3. Then I traverse it to the top and look at the situation, when I have just 2 components, e.g. 011 - I ignore component #1 and look at minimal possible solution for components #2 and #3 together

– Влад Казимиров
Mar 26 at 12:04













Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

– Yonlif
Mar 26 at 12:43





Ok! Things are more clear now. I still don't understand why there are 5 wires and not 3 for minimal solution.

– Yonlif
Mar 26 at 12:43













Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

– גלעד ברקן
Mar 26 at 13:11






Can more than one component be connected to a single wire? Can wires go left or right in addition to up or down?

– גלעד ברקן
Mar 26 at 13:11













1 Answer
1






active

oldest

votes


















1














For now I can't really see something better or more clever than a branch and bound approach to solve that. It is somehow similar to what you have proposed, but does not have redundant calculations.

Here it is briefly described as a pythonic pseudocode:



def BnB(grid, components):
queue = new_priority_queue() # classic priority queue
empty_sol = [None for i in range(len(components))] # we create an 'empty' solution
queue.push((0, 0, empty_sol)) # we push an initial empty solution on the queue (a tuple total len, index, solution)
best_length_so_far = infinite # we keep track of the best solution seen so far
best_sol_so_far = None
while not queue.is_empty():
length, index, solution = queue.pop()
if index == len(components): # it is a feasible solution
if best_len_so_far > length:
best_len_so_far = length
best_sol_so_far = solution
elif length < best_len_so_far:
# check if components[index] can have its wire 'DOWN'
if can_put_wire(grid, components, index, 'DOWN'):
length_to_add = path_len(grid, component, index, 'DOWN')
new_sol = copy(solution)
new_sol[index] = 'DOWN'
queue.push((length + length_to_add, index + 1, new_sol))
# do the same thing for the other directions
if can_put_wire(grid, components, index, 'UP'):
....
if can_put_wire(grid, components, index, 'LEFT'):
....
if can_put_wire(grid, components, index, 'RIGHT'):
....
return best_sol_so_far


The exploration of the solutions tree would depend on how you set the priorities on your queue. The choice of the component to consider (rather than to take them in the order like in the code above) could also help to have solutions faster.
This will not be efficient (complexity in time exponential w.r.t the number of components), but it can find the solution.



Another possibility is to use ILP (integer linear programming) to solve the problem. It can be rather easily described with linear constraints, and would enjoy all the optimizations offered by a LP solver.






share|improve this answer























  • I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

    – Влад Казимиров
    Mar 26 at 16:13











  • Please supply some educational counter-examples.

    – Prune
    Mar 26 at 22:49











  • Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

    – Влад Казимиров
    Mar 26 at 23:00







  • 1





    My mistake, I guess, this one is the solution

    – Влад Казимиров
    Mar 29 at 9:23











  • Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

    – m.raynal
    Mar 29 at 9:37










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55353654%2ffind-minimal-wire-connection%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














For now I can't really see something better or more clever than a branch and bound approach to solve that. It is somehow similar to what you have proposed, but does not have redundant calculations.

Here it is briefly described as a pythonic pseudocode:



def BnB(grid, components):
queue = new_priority_queue() # classic priority queue
empty_sol = [None for i in range(len(components))] # we create an 'empty' solution
queue.push((0, 0, empty_sol)) # we push an initial empty solution on the queue (a tuple total len, index, solution)
best_length_so_far = infinite # we keep track of the best solution seen so far
best_sol_so_far = None
while not queue.is_empty():
length, index, solution = queue.pop()
if index == len(components): # it is a feasible solution
if best_len_so_far > length:
best_len_so_far = length
best_sol_so_far = solution
elif length < best_len_so_far:
# check if components[index] can have its wire 'DOWN'
if can_put_wire(grid, components, index, 'DOWN'):
length_to_add = path_len(grid, component, index, 'DOWN')
new_sol = copy(solution)
new_sol[index] = 'DOWN'
queue.push((length + length_to_add, index + 1, new_sol))
# do the same thing for the other directions
if can_put_wire(grid, components, index, 'UP'):
....
if can_put_wire(grid, components, index, 'LEFT'):
....
if can_put_wire(grid, components, index, 'RIGHT'):
....
return best_sol_so_far


The exploration of the solutions tree would depend on how you set the priorities on your queue. The choice of the component to consider (rather than to take them in the order like in the code above) could also help to have solutions faster.
This will not be efficient (complexity in time exponential w.r.t the number of components), but it can find the solution.



Another possibility is to use ILP (integer linear programming) to solve the problem. It can be rather easily described with linear constraints, and would enjoy all the optimizations offered by a LP solver.






share|improve this answer























  • I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

    – Влад Казимиров
    Mar 26 at 16:13











  • Please supply some educational counter-examples.

    – Prune
    Mar 26 at 22:49











  • Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

    – Влад Казимиров
    Mar 26 at 23:00







  • 1





    My mistake, I guess, this one is the solution

    – Влад Казимиров
    Mar 29 at 9:23











  • Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

    – m.raynal
    Mar 29 at 9:37















1














For now I can't really see something better or more clever than a branch and bound approach to solve that. It is somehow similar to what you have proposed, but does not have redundant calculations.

Here it is briefly described as a pythonic pseudocode:



def BnB(grid, components):
queue = new_priority_queue() # classic priority queue
empty_sol = [None for i in range(len(components))] # we create an 'empty' solution
queue.push((0, 0, empty_sol)) # we push an initial empty solution on the queue (a tuple total len, index, solution)
best_length_so_far = infinite # we keep track of the best solution seen so far
best_sol_so_far = None
while not queue.is_empty():
length, index, solution = queue.pop()
if index == len(components): # it is a feasible solution
if best_len_so_far > length:
best_len_so_far = length
best_sol_so_far = solution
elif length < best_len_so_far:
# check if components[index] can have its wire 'DOWN'
if can_put_wire(grid, components, index, 'DOWN'):
length_to_add = path_len(grid, component, index, 'DOWN')
new_sol = copy(solution)
new_sol[index] = 'DOWN'
queue.push((length + length_to_add, index + 1, new_sol))
# do the same thing for the other directions
if can_put_wire(grid, components, index, 'UP'):
....
if can_put_wire(grid, components, index, 'LEFT'):
....
if can_put_wire(grid, components, index, 'RIGHT'):
....
return best_sol_so_far


The exploration of the solutions tree would depend on how you set the priorities on your queue. The choice of the component to consider (rather than to take them in the order like in the code above) could also help to have solutions faster.
This will not be efficient (complexity in time exponential w.r.t the number of components), but it can find the solution.



Another possibility is to use ILP (integer linear programming) to solve the problem. It can be rather easily described with linear constraints, and would enjoy all the optimizations offered by a LP solver.






share|improve this answer























  • I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

    – Влад Казимиров
    Mar 26 at 16:13











  • Please supply some educational counter-examples.

    – Prune
    Mar 26 at 22:49











  • Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

    – Влад Казимиров
    Mar 26 at 23:00







  • 1





    My mistake, I guess, this one is the solution

    – Влад Казимиров
    Mar 29 at 9:23











  • Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

    – m.raynal
    Mar 29 at 9:37













1












1








1







For now I can't really see something better or more clever than a branch and bound approach to solve that. It is somehow similar to what you have proposed, but does not have redundant calculations.

Here it is briefly described as a pythonic pseudocode:



def BnB(grid, components):
queue = new_priority_queue() # classic priority queue
empty_sol = [None for i in range(len(components))] # we create an 'empty' solution
queue.push((0, 0, empty_sol)) # we push an initial empty solution on the queue (a tuple total len, index, solution)
best_length_so_far = infinite # we keep track of the best solution seen so far
best_sol_so_far = None
while not queue.is_empty():
length, index, solution = queue.pop()
if index == len(components): # it is a feasible solution
if best_len_so_far > length:
best_len_so_far = length
best_sol_so_far = solution
elif length < best_len_so_far:
# check if components[index] can have its wire 'DOWN'
if can_put_wire(grid, components, index, 'DOWN'):
length_to_add = path_len(grid, component, index, 'DOWN')
new_sol = copy(solution)
new_sol[index] = 'DOWN'
queue.push((length + length_to_add, index + 1, new_sol))
# do the same thing for the other directions
if can_put_wire(grid, components, index, 'UP'):
....
if can_put_wire(grid, components, index, 'LEFT'):
....
if can_put_wire(grid, components, index, 'RIGHT'):
....
return best_sol_so_far


The exploration of the solutions tree would depend on how you set the priorities on your queue. The choice of the component to consider (rather than to take them in the order like in the code above) could also help to have solutions faster.
This will not be efficient (complexity in time exponential w.r.t the number of components), but it can find the solution.



Another possibility is to use ILP (integer linear programming) to solve the problem. It can be rather easily described with linear constraints, and would enjoy all the optimizations offered by a LP solver.






share|improve this answer













For now I can't really see something better or more clever than a branch and bound approach to solve that. It is somehow similar to what you have proposed, but does not have redundant calculations.

Here it is briefly described as a pythonic pseudocode:



def BnB(grid, components):
queue = new_priority_queue() # classic priority queue
empty_sol = [None for i in range(len(components))] # we create an 'empty' solution
queue.push((0, 0, empty_sol)) # we push an initial empty solution on the queue (a tuple total len, index, solution)
best_length_so_far = infinite # we keep track of the best solution seen so far
best_sol_so_far = None
while not queue.is_empty():
length, index, solution = queue.pop()
if index == len(components): # it is a feasible solution
if best_len_so_far > length:
best_len_so_far = length
best_sol_so_far = solution
elif length < best_len_so_far:
# check if components[index] can have its wire 'DOWN'
if can_put_wire(grid, components, index, 'DOWN'):
length_to_add = path_len(grid, component, index, 'DOWN')
new_sol = copy(solution)
new_sol[index] = 'DOWN'
queue.push((length + length_to_add, index + 1, new_sol))
# do the same thing for the other directions
if can_put_wire(grid, components, index, 'UP'):
....
if can_put_wire(grid, components, index, 'LEFT'):
....
if can_put_wire(grid, components, index, 'RIGHT'):
....
return best_sol_so_far


The exploration of the solutions tree would depend on how you set the priorities on your queue. The choice of the component to consider (rather than to take them in the order like in the code above) could also help to have solutions faster.
This will not be efficient (complexity in time exponential w.r.t the number of components), but it can find the solution.



Another possibility is to use ILP (integer linear programming) to solve the problem. It can be rather easily described with linear constraints, and would enjoy all the optimizations offered by a LP solver.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 13:23









m.raynalm.raynal

1,5379 silver badges20 bronze badges




1,5379 silver badges20 bronze badges












  • I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

    – Влад Казимиров
    Mar 26 at 16:13











  • Please supply some educational counter-examples.

    – Prune
    Mar 26 at 22:49











  • Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

    – Влад Казимиров
    Mar 26 at 23:00







  • 1





    My mistake, I guess, this one is the solution

    – Влад Казимиров
    Mar 29 at 9:23











  • Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

    – m.raynal
    Mar 29 at 9:37

















  • I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

    – Влад Казимиров
    Mar 26 at 16:13











  • Please supply some educational counter-examples.

    – Prune
    Mar 26 at 22:49











  • Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

    – Влад Казимиров
    Mar 26 at 23:00







  • 1





    My mistake, I guess, this one is the solution

    – Влад Казимиров
    Mar 29 at 9:23











  • Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

    – m.raynal
    Mar 29 at 9:37
















I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

– Влад Казимиров
Mar 26 at 16:13





I guess branch and bounds method won't always give the best solution. It will be close to optimal, but not the optimal one

– Влад Казимиров
Mar 26 at 16:13













Please supply some educational counter-examples.

– Prune
Mar 26 at 22:49





Please supply some educational counter-examples.

– Prune
Mar 26 at 22:49













Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

– Влад Казимиров
Mar 26 at 23:00






Ok, given the following input: 14n 3 1 8 3 10 2 8 It will output: 12 LEFT LEFT DOWN But the correct output is: 11 LEFT UP UP This will happen, because of the order of components traversal. It will mark the solution, where you have to make "bad direction" on the second point as bad, and thus will connect 2nd component to the closest edge, which is the left one. Although this solution is good enough, it's not the optimal one. Just draw the picture to understand

– Влад Казимиров
Mar 26 at 23:00





1




1





My mistake, I guess, this one is the solution

– Влад Казимиров
Mar 29 at 9:23





My mistake, I guess, this one is the solution

– Влад Казимиров
Mar 29 at 9:23













Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

– m.raynal
Mar 29 at 9:37





Yes, branch and bound is an exact method which rovides an optimal answer. The way I see it, it is just an improvement of a purely recursive (or backtracking) approach, where some branches of the tree are being pruned if they do not have any chance to carry one optimal solution leaf.

– m.raynal
Mar 29 at 9:37








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55353654%2ffind-minimal-wire-connection%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해