Constrained N-Rook Number of Solutions - algorithm

The purpose of this post is mainly for keywords for related researches.
Unconstrained N-Rook Problem
Count all possible arrangements of N rooks on an N by M (N<=M) chessboard so that no rooks are attacking each other.
The solution is trivial: C(M,N)N!
Constrained N-Rook Problem
You cannot put a rook at certain places of the chessboard.
For example, if the chessboard is presented as a 0-1 matrix, where 0 are the places you cannot put a rook at. So the solution for the matrix
1 1 1
1 1 1
0 1 1
is 4:
R . . | R . . | . R . | . . R
. R . | . . R | R . . | R . .
. . R | . R . | . . R | . R .
Related Problem
A backtracking algorithm can be easily modified from N-Queen problem. However, now I want to solve a problem for around N=28. This solution is too huge to count 1 by 1, even wiki said
The 27×27 board is the highest-order board that has been completely enumerated.
Chances to Speed Up
There are a few chances I thought of so far to speed up the algorithm.
=====Factorial for Unconstrained Submatrix=====
This is a Divide and Conquer method. e.g. The matrix above
1 1 1
1 1 1
0 1 1
can be divided as
A B
1 1 1 | 0 1 1
1 1 1 |
and the solution is equal to sol(A)*sol(B), where sol(A)=2! which can be calculated at once (factorial is much faster than backtracking).
=============Rearrangement=============
Sometimes rearrangement can help to divide the subproblem. e.g. The matrix
1 1 1
1 0 1
1 1 1
is equivalent to
1 1 1
1 1 1
0 1 1
Question
What is the keyword for this kind of problem?
Are there any efficient developed technique for this kind of problem?

The rook polynomial, rook coefficient, restricted permutations and permanent are the keywords.
From Theorem 3.1 of Algorithm for Finding the Coefficients of Rook Polynomials
The number of arrangements of n objects with restriction board B is equal to permanent of B.
Here B is what we defined in the question, a 0-1 matrix where 1 is ok, 0 is restricted for a rook.
So now we need to efficiently calculate the permanent of a matrix.
Fortunately, from this code golf, Ton Hospel uses Glynn formula with a Gray code and Ryser formula, and reach about 57 seconds on the tester's system for n=36, which is quite enough for the questioner's case.

Related

Is there an algorithm that divide a square cell grid map into 3 or 4 equal spaces?

So for example I have divide my map into something like this:
click on link
the matrix representative would be
0 1 0 1 0
1 1 1 1 0
0 1 1 1 1
0 1 0 0 0
one of the way I could divide it into even-ish would be:
click to see
where total square is 11 and since 11/3 gives us a decimal, I need to have 2 space with 4 square and one space with 3 squares.
but I don't know an algorithm that will be able to divide a small map like that.
there is probably a code that will be able to solve that particular map, but what if it is like :
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 0 1
Each value is a square in the map and 1 is the square that should be considered. 0 is an empty/null space that is not part of the map and should not be taken into consideration when dividing the map.
So far I try a for loop adding all value and divide by 3 to determine how many squares is needed for each space. Also, if I get a decimal, then one space can have one more square than the other. So in this problem there is 36 squares so if I try to divide it into 3 space, then each space would have 12 squares.
So I am looking to see if there is an algorithm that will be able to solve all types of map.
This is actually NP-hard for k>=2, where you want k=3 or k=4:
theorem 2.2 in On the complexity of partitioning graphs into connected subgraphs - M.E. DYER, A.M. FRIEZE
You can get a decent answer by greedily removing nodes from your graph, and backtracking if you can't merge the remaining nodes.
It would help if you gave a more rigorous definition of 'even-ish' - for example, consider a map with 13 nodes - Would you rather have divisions of size (4,4,5), (3,3,3,4), (4,4,4,1), (5,5,3), or (4,4,3,2)?

Hashing every combination of tic tac toe table

I'm working on an algorithm to determine if a tic tac toe model has a winner or not. There's a little twist though-- the function has_won? is being called multiple times. Consequently, the author of the algorithm problem in the book I'm reading (Cracking the Coding Interview) suggests generating each of the 2^9 possible tables and hashing them to a table.
To generate unique keys for each permutation, she represents each board as an integer (board is initially a char array). The integer is generated as such: (3^0)v0 + (3^1)v1 + (3^2)v2+...+(3^8)v8 where v is a 0 if the space is empty, 1 if it's an X, and 2 if it's a O.
Here's what I'm not following. I understand why she did what she did. But what's the guarantee that there won't be another board in the roughly 20,000 possible boards that won't share the same integer key value with that representation? She didn't provide a proof, and I'm not able to intuitively grasp why that's a unique number.
Let's try to see how it works with a simple example. Suppose the board has only two spaces. I know that's not a good game, but just as a first step use it to show how the number code works. In this case the integer is in your notation
(3^0)v0 + (3^1)v1
where v0 and v1 tell us whether the two spaces are empty (0) have a X (1) or have a O (2). Now enumerate the cases:
_ _ (3^0) 0 + (3^1) 0 = 0
X _ (3^0) 1 + (3^1) 0 = 1
O _ (3^0) 2 + (3^1) 0 = 2
Notice that filling up the left space only generates numbers less than 3. Now fill up the right hand space.
_ X (3^0) 0 + (3^1) 1 = 3
_ O (3^0) 0 + (3^1) 2 = 6
Notice that in filling the right hand space we only get multiples of three. Now do the rest.
X X (3^0) 1 + (3^1) 1 = 4
O X (3^0) 2 + (3^1) 1 = 5
X O (3^0) 1 + (3^1) 2 = 7
O O (3^0) 2 + (3^1) 2 = 8
Now we can see that each configuration corresponds to one and only one integer. Further, we can get the configuration out of the integer by integer division. Take the second last case, 7. Divide it by three to get 2 with a remainder of 1. 2 is the configuration of the right hand square and 1 is the configuration of the left. This works for all of the examples above.
If you try this with more than two squares, you'll get the same result. The reason I know that's true, and the way you can get the proof you ask for in your post is to realise that a base three number system keeps the state of each square in one of its digits. That's how the encoding you describe works and that's why each term in the integer encoding has a power of three. This is sufficient I think to show that the integer generated is unique.
One more possible clarification might be to imagine squares that can be in any one of ten states. Call these 0 to 9. Then any ordinary base ten number, for example
234
keeps the state of one and only one square in each digit, and each configuration of squares gives you one and only one base ten number. Write this number in the notation you give in your post
(10^0) 4 + (10^1) 3 + (10^2) 2 = 234
and we have v0=4, v1=3, and v2=2.

Which algorithms are there to find the Smallest Set of Smallest Rings?

I have an unweighted undirected connected graph. Generally, it's a chemical compound with lots of cycles side by side. The problem is common in this field and is called like the title says. Good algorithm is Horton's one. However, I don't seem to find any exact information about the algorithm, step by step.
Clearly speaking my problem is this, Algorithm for finding minimal cycles in a graph , but unfortunately the link to the site is disabled.
I only found python code of Figueras algorithm but Figuearas does not work in every case. Sometimes it doesn't find all rings.
The problem is similar to this, Find all chordless cycles in an undirected graph , I tried it but didn't work for more complex graphs like mine.
I found 4-5 sources of needed information, but the algorithm is not fully explained at all.
I don't seem to find any algorithm for SSSR although it seems a common problem, mainly in the chemistry field.
Horton's algorithm is pretty simple. I'll describe it for your use case.
For each vertex v, compute a breadth-first search tree rooted at v. For each edge wx such that v, w, x are pairwise distinct and such that the least common ancestor of w and x is v, add a cycle consisting of the path from v to w, the edge wx, and the path from x back to v.
Sort these cycles by size nondecreasing and consider them in order. If the current cycle can be expressed as the "exclusive OR" of cycles considered before it, then it is not part of the basis.
The test in Step 2 is the most complicated part of this algorithm. What you need to do, basically, is write out the accepted cycle and the candidate cycle as a 0-1 incidence matrix whose rows are indexed by cycle and whose columns are indexed by edge, then run Gaussian elimination on this matrix to see whether it makes an all-zero row (if so, discard the candidate cycle).
With some effort, it's possible to save the cost of re-eliminating the accepted cycles every time, but that's an optimization.
For example, if we have a graph
a---b
| /|
| / |
|/ |
c---d
then we have a matrix like
ab ac bc bd cd
abca 1 1 1 0 0
bcdb 0 0 1 1 1
abdca 1 1 0 1 1
where I'm cheating a bit because abdca is not actually one of the cycles generated in Step 1.
Elimination proceeds as follows:
ab ac bc bd cd
1 1 1 0 0
0 0 1 1 1
1 1 0 1 1
row[2] ^= row[0];
ab ac bc bd cd
1 1 1 0 0
0 0 1 1 1
0 0 1 1 1
row[2] ^= row[1];
ab ac bc bd cd
1 1 1 0 0
0 0 1 1 1
0 0 0 0 0
so that set of cycles is dependent (don't keep the last row).

How to solve 5 * 5 Cube in efficient easy way

There is 5*5 cube puzzle named Happy cube Problem where for given mat , need to make a cube .
http://www.mathematische-basteleien.de/cube_its.htm#top
Its like, 6 blue mats are given-
From the following mats, Need to derive a Cube -
These way it has 3 more solutions.
So like first cub
For such problem, the easiest approach I could imagine was Recursion based where for each cube, I have 6 position , and for each position I will try check all other mate and which fit, I will go again recursively to solve the same. Like finding all permutations of each of the cube and then find which fits the best.So Dynamic Programming approach.
But I am making loads of mistake in recursion , so is there any better easy approach which I can use to solve the same?
I made matrix out of each mat or diagram provided, then I rotated them in each 90 clock-wise 4 times and anticlock wise times . I flip the array and did the same, now for each of the above iteration I will have to repeat the step for other cube, so again recursion .
0 0 1 0 1
1 1 1 1 1
0 1 1 1 0
1 1 1 1 1
0 1 0 1 1
-------------
0 1 0 1 0
1 1 1 1 0
0 1 1 1 1
1 1 1 1 0
1 1 0 1 1
-------------
1 1 0 1 1
0 1 1 1 1
1 1 1 1 0
0 1 1 1 1
0 1 0 1 0
-------------
1 0 1 0 0
1 1 1 1 1
0 1 1 1 0
1 1 1 1 1
1 1 0 1 0
-------------
1st - block is the Diagram
2nd - rotate clock wise
3rd - rotate anti clockwise
4th - flip
Still struggling to sort out the logic .
I can't believe this, but I actually wrote a set of scripts back in 2009 to brute-force solutions to this exact problem, for the simple cube case. I just put the code on Github: https://github.com/niklasb/3d-puzzle
Unfortunately the documentation is in German because that's the only language my team understood, but source code comments are in English. In particular, check out the file puzzle_lib.rb.
The approach is indeed just a straightforward backtracking algorithm, which I think is the way to go. I can't really say it's easy though, as far as I remember the 3-d aspect is a bit challenging. I implemented one optimization: Find all symmetries beforehand and only try each unique orientation of a piece. The idea is that the more characteristic the pieces are, the less options for placing pieces exist, so we can prune early. In the case of many symmetries, there might be lots of possibilities and we want to inspect only the ones that are unique up to symmetry.
Basically the algorithm works as follows: First, assign a fixed order to the sides of the cube, let's number them 0 to 5 for example. Then execute the following algorithm:
def check_slots():
for each edge e:
if slot adjacent to e are filled:
if the 1-0 patterns of the piece edges (excluding the corners)
have XOR != 0:
return false
if the corners are not "consistent":
return false
return true
def backtrack(slot_idx, pieces_left):
if slot_idx == 6:
# finished, we found a solution, output it or whatever
return
for each piece in pieces_left:
for each orientation o of piece:
fill slot slot_idx with piece in orientation o
if check_slots():
backtrack(slot_idx + 1, pieces_left \ {piece})
empty slot slot_idx
The corner consistency is a bit tricky: Either the corner must be filled by exactly one of the adjacent pieces or it must be accessible from a yet unfilled slot, i.e. not cut off by the already assigned pieces.
Of course you can ignore to drop some or all of the consistency checks and only check in the end, seeing as there are only 8^6 * 6! possible configurations overall. If you have more than 6 pieces, it becomes more important to prune early.

Converting a number into a special base system

I want to convert a number in base 10 into a special base form like this:
A*2^2 + B*3^1 + C*2^0
A can take on values of [0,1]
B can take on values of [0,1,2]
C can take on values of [0,1]
For example, the number 8 would be
1*2^2 + 1*3 + 1.
It is guaranteed that the given number can be converted to this specialized base system.
I know how to convert from this base system back to base-10, but I do not know how to convert from base-10 to this specialized base system.
In short words, treat every base number (2^2, 3^1, 2^0 in your example) as weight of an item, and the whole number as the capacity of a bag. This problem wants us to find a combination of these items which they fill the bag exactly.
In the first place this problem is NP-complete. It is identical to the subset sum problem, which can also be seen as a derivative problem of the knapsack problem.
Despite this fact, this problem can however be solved by a pseudo-polynomial time algorithm using dynamic programming in O(nW) time, which n is the number of bases, and W is the number to decompose. The details can be find in this wikipedia page: http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming and this SO page: What's it called when I want to choose items to fill container as full as possible - and what algorithm should I use?.
Simplifying your "special base":
X = A * 4 + B * 3 + C
A E {0,1}
B E {0,1,2}
C E {0,1}
Obviously the largest number that can be represented is 4 + 2 * 3 + 1 = 11
To figure out how to get the values of A, B, C you can do one of two things:
There are only 12 possible inputs: create a lookup table. Ugly, but quick.
Use some algorithm. A bit trickier.
Let's look at (1) first:
A B C X
0 0 0 0
0 0 1 1
0 1 0 3
0 1 1 4
0 2 0 6
0 2 1 7
1 0 0 4
1 0 1 5
1 1 0 7
1 1 1 8
1 2 0 10
1 2 1 11
Notice that 2 and 9 cannot be expressed in this system, while 4 and 7 occur twice. The fact that you have multiple possible solutions for a given input is a hint that there isn't a really robust algorithm (other than a look up table) to achieve what you want. So your table might look like this:
int A[] = {0,0,-1,0,0,1,0,1,1,-1,1,1};
int B[] = {0,0,-1,1,1,0,2,1,1,-1,2,2};
int C[] = {0,1,-1,0,2,1,0,1,1,-1,0,1};
Then look up A, B, C. If A < 0, there is no solution.

Resources