0

I have a 2-dimensional array that looks like this:

1 1 0 0 1
1 0 1 1 0
0 0 1 1 0
1 1 0 1 1
0 0 1 1 1

I'm trying to figure out a way to identify the longest contiguous chain of 1's going either across or down. In this case, it starts at column 4, row 2, and its length is 4, going down.

I was thinking of using recursion, but I'm running into some issues keeping track of position, especially when encountering a 0.

So far, I have something along the lines of this (for checking across only):

main() {
    ...
    for(i = 0; i < n; i++)
      for(j = 0; j < n; j++)
        if (G[i][j] == 1) {
          CheckAcross(i, j, n);
        }
    ...
}

void CheckAcross (int i, int j, int n) {
     if (i < 0 || i >= n || j < 0 || j >= n) return; // outside of grid
     if (G[i][j] == 0 ) return; //0 encountered
     G[i][j] = WordCount + 1;
     CheckAcross(i, j + 1, n);

}

where G[][] is the 2-dimensional array containing the 1's and 0's, n is the number of rows/columns, i is the row number and j is the column number.

Thanks for any assistance in advance!

Zachary Subran
  • 105
  • 1
  • 1
  • 7

2 Answers2

0

Your current answer will take O(n3) time; to evaluate a single line, you check every possible start and end position (O(n) possibilities for each), and there are n lines.

Your algorithm is correct, but let's see if we can improve on the running time.

The problem might become simpler if we break it into simpler problems, i.e. "What is the longest contiguous chain of 1s in this 1-dimensional array?". If we solve it 2n times, then we have our answer, so we just need to get this one down to smaller than O(n2) for an improvement.

Well, we can simply go through the line, remembering the position (start and end) and length of the longest sequence of 1s. This takes O(n) time, and is optimal (if the sequence is all 1s or 0s, we would have to read every element to know where the start/end of the longest sequence is).

Then we can simply solve this for every row and every column, in O(n2) time.

  • If you want to stick to your own solution, you can easily swap rows and columns by simply swapping the indices around, and your implementation is done. –  May 12 '11 at 04:33
0

Create a new n-by-n matrix called V. This will store, for each cell, the number of 1s at that cell and immediately above it. This will be O(n^2).

checkAllVertical(int n) {
    V = malloc(....) // create V, an n-by-n matrix initialized to zero
    for(int r=0; r<n; r++) {
      for(int c=0; c<n; c++) {
        if(G[r][c]=1) {
          if(r==0)
            V[r][c] = 1;
          else
            V[r][c] = 1 + V[r][c];
        }
      }
    }
}

You don't really need to allocate all of V. One row at a time would suffice.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88