The fastest algorithm for returning max length of consecutive same value fields of matrix? -



The fastest algorithm for returning max length of consecutive same value fields of matrix? -

here given example:

we have function takes 1 matrix , it's number of columns , it's number of rows , returns int (this gonna length). example:

int function (int** matrix, int n, int m)

the question what's fastest algorithm implementing function returns maximum length of consecutive fields same value (doesn't matter if same values in 1 column or in 1 row, in illustration on image it's 5 fields of 1 column value 8)? values can 0-255 (grayscale example). in given illustration function should homecoming 5.

if bottleneck , matrix large, first optimization seek create 1 pass on matrix in sequential memory order (row-by-row in c or c++) rather two. because it's expensive traverse 2d array in other direction. cache , paging behavior worst possible.

for need row-sized array track number of consecutive values in current run within each column.

int function (int a[][], int m, int n) { if (n <= 0 || m <= 0) homecoming 0; int longest_run_len = 1; // accumulator homecoming value. int current_col_run_len[n]; // accumulators each column int current_row_run_len = 1; // accumulator current row. // initialize column accumulators , check first row. current_col_run_len[0] = 1; (int j = 1; j < n; j++) { current_col_run_len[j] = 1; if (a[0][j] == a[0][j-1]) { if (++current_row_run_len > longest_run_len) longest_run_len = current_row_run_len; } else current_row_run_len = 1; } // rest of rows... (int = 1; < m; i++) { // first column: if (a[i][0] == a[i-1][0]) { if (++current_col_run_len[0] > longest_run_len) longest_run_len = current_col_run_len[0]; } else current_col_run_len[0] = 1; // other columns. current_row_run_len = 1; (int j = 1; j < n; j++) { if (a[i][j] == a[i][j-1]) { if (++current_row_run_len > longest_run_len) longest_run_len = current_row_run_len; } else current_row_run_len = 1; if (a[i][j] == a[i-1][j]) { if (++current_col_run_len[j] > longest_run_len) longest_run_len = current_col_run_len[j]; } else current_col_run_len[j] = 1; } } homecoming longest_run_len; }

algorithm matrix

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -