Dynamic Programming

Last weekend, I had the opportunity to confront a dynamic programming problem. I always liked dynamic programming algorithms but didn't understand how people came up with them.

My problem was the following: given a piece of text, how do you lay it out in a shape as close as possible to a square? For example, this paragraph would be rendered as:

  My problem was the 
  following: given a piece 
  of text, how do you lay it 
  out in a shape as close as 
  possible to a square? For 
  example, this paragraph 
  would be rendered as: 
Here, the maximum width of the rows is approximately equal to the height of the whole paragraph. This is what I wanted.

First thing to do was to separate the text into words, which is pretty straightforward. Then I got the width of each word from the GUI library, since I can't work on length alone. I called the width array W, where W[i] is the width of the word #i, in pixels.

After that, I figured that the following table would be useful. As we are building rows, we add the widths of the words together to find the width of the row. If we tried to do this by trial and error, we would end up adding lots of numbers over and over again. I could store the result of these additions in a table. I don't have to but it would be nice.

Our first table, A is a two dimensional array of integers. The first axis is the number of the word starting a row. The second axis is the number of the word ending the row. The value is the width of the row given the starting and ending words. For example A[3][5] would be the width of a row starting with word #3 and ending with word #5. Here, the word #5 is included in the row. Building this table is pretty straightforward.

  for(i=0;i<N;i++) {
    A[i][i]= W[i];
      A[i][j]= A[i][j-1] + width_of_space + W[j];
As I understand it, the first step of creating a dynamic programming algorithm is to decide what you want to compute. In other words, you need to approach the problem in a way that enables you to solve bigger problems using solutions of smaller problems.

My initial instinct was to do a search using the array A. This turned out to require O(2N) time, but was useful in directing me to a solution. Assume that we're doing a search on the array A. When we have came to the word #k, we have used R rows and have a current maximum width of W. Now we start a row at word #k and use 1 row or 2 rows etc. I realised that when we're at this position, it's sufficient to calculate the case with 1 row only once, the case with 2 rows only once etc. No matter how we came to word #k (using 1 row or 2 rows .. etc), the solution starting from word #k is always the same, it doesn't affect our search from this point on.

So I thought I could cache the results of these computations. I would have a two dimensional array of integers, called M. The first axis would correspond to a word number. So, M[i] would correspond to the situation where word #i starts a row, consistent with our search algorithm. The second axis would be the number of rows used from this point on. M[i][1] would correspond to the situation where a row starts from word #i and the rest of the text is put on the same row. M[i][2] corresponds to the same situtation, but the text scattered over two rows etc. The value stored at M[i][j] would be the minimum width required in order to render the rest of the text with j rows and starting from word #i.

I then realized that the array M was in fact the solution to the problem. M[0] would have the minimum required width for all choices of number of rows. I could select the best one from M[0] and then proceed from there to form a complete solution. So, I set out to compute M without doing any search at all.

So, I tried to find a mathematical model for the elements of M. For the last word, there are no choices at all. Therefore, its value is already known.

  M[N-1][1]= A[N-1][N-1] = W[N-1]
Since we can't divide the last word into two, this is the only valid value in M[N-1]. We observe that for the one-row situation, the first half of the above equation holds true for all words. If you start a row with a word and insist that all following text to be put on the same row, then the minimum width of that row is the same as the addition of widths of all words from the chosen word until the end of the text.
  M[k][1]= A[k][N-1]
Another observation is that, if we start a row from word k, then the maximum number of rows needed (from that point on) is N-k. So,
  M[k][N-k+p] = invalid
for all positive p. Now we can proceed with the actual calculation. Let's assume that we already know M[k][r], the minimum width required for the text starting at word k, using r rows. What can we deduce from here?

We know that the previous row would end at word k-1. It could start at any word from 0 to k-1. We would be working with r+1 rows: we have r rows already starting from word k and would have one more (the previous one). So, we can update the M matrix as follows:

     M[j][r+1]= min( M[j][r+1],  max(A[j][k-1], M[k][r]) );
Here, we update the solution to M[j][r+1] only if the new solution (which has the next row starting at k) is better than the known solution. We fill the matrix with sentinels before this so that every element in it gets a sensible value. The second term is width of the combination of the previous row with the set of rows calculated so far. M[k][r] is the width of the rows calculated. A[j][k-1] is the width of the row starting at word j and ending at word k-1. So, the maximum of these two gives us the width of their combination.

We will do the above loop for all row-choices of word k. So, we wrap it in another loop:

     M[j][r+1]= min( M[j][r+1],  max(A[j][k-1], M[k][r]) );
We need to process all words in this manner. We need another loop to do that. However, this loop shall start from the end. At the start of the algorithm only M[N-1] is fully known. The others contain sentinels and one value at column #1. Therefore this loop needs to go thru the words in backwards order. It will also not process word #0 since there is nothing we can do with the values of M[0].
     M[j][r+1]= min( M[j][r+1],  max(A[j][k-1], M[k][r]) );
Here, we could probably exchange the order of the two inner loops but it makes more sense to process word j for given M[k][r]. In any case, the matrix row M[0] holds all the solutions when the code ends.

However, there is one shortcoming. Although we know the minimum widths required, there is no way to find out which selections of row-start words make these happen. To find that out, we need to store our solution when constructing the matrix M. I'll make a new two dimensional array Y. Its axises are the same as M. However, the value holds the number of the word ending the row.

   for(j=k-1;j>=0;j--) {
     combined= max(A[j][k-1], M[k][r]);
     if (combined<M[j][r+1]) {
       M[j][r+1]= combined;
       Y[j][r+1]= k-1;
Now we have the optimal width for r rows in M[k][r] and the end of the row first for that solution in Y[k][r]. The start of the row is of course, k.

All that is left is to find the best solution using M[0] and extract the list of row-start words. Since we are aiming for a most-square layout, we will try to minimize the circumference of the resulting layout rectangle. Other aspect ratios can be forced by using a different formula for the circumference. i.e. by multiplying the row_height or M[0][i] with a constant.

  best= M[0][1]+row_height*1;
  nrows= 1;
  for(i=2;i<=n;i++) {
    half_circ= M[0][i]+row_height*i;
    if (half_circ<best) {
      best= half_circ;
      nrows= i;
Once we have selected the optimum row width from M[0], we can proceed with the construction of the rows. The first one is of course at word 0. The resst can easily be extracted from the Y matrix.
  nsol= 0;
  sol[nsol++]= 0;

  while(nrows) {
    sol[nsol]= Y[sol[nsol-1]][nrows]+1;
    nrows--; nsol++;
  return nsol-1;
That's it for my problem. Now I have a couple of observations regarding dynamic programming: Here is the uuencode of my implementation.
begin 644 square.c.gz