Comments on: Programming Interview Questions 2: Matrix Region Sum /2011/09/20/programming-interview-questions-2-matrix-region-sum/?utm_source=rss&utm_medium=rss&utm_campaign=programming-interview-questions-2-matrix-region-sum Information Retrieval and Machine Learning Mon, 23 Jan 2012 19:14:24 +0000 hourly 1 http://wordpress.org/?v=3.3 By: Prakash /2011/09/20/programming-interview-questions-2-matrix-region-sum/#comment-855 Prakash Mon, 19 Dec 2011 13:03:30 +0000 /?p=478#comment-855 precompute can be done like this .. sum[0][0] = matrix[0][0] for first row sum[0][j] = sum[0][j-1] + matrix[0][j] for first column sum[i][0] = sum[i-1][0] + matrix[i][0] for all other rows and columns sum[i][j] = matrix[i][j] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] <code> // a is input array .. filled with sample inputs int a[][] = { {1,1,1,1,1}, {2,2,2,2,2}, {3,3,3,3,3}, {4,4,4,4,4}, {5,5,5,5,5} }; int sum[][] = new int[a.length][a[0].length]; sum[0][0] = a[0][0]; for(int i=1;i<a.length;i++){ sum[i][0] = sum[i-1][0] + a[i][0]; } for(int j=1;j<a[0].length;j++){ sum[0][j] = sum[0][j-1] + a[0][j]; } for(int i=1; i<a.length;i++) { for(int j=1; j<a[0].length;j++) { sum[i][j] = a[i][j] + sum[i][j-1] + sum[i-1][j] - sum[i-1][j-1]; } } </code> precompute can be done like this ..

sum[0][0] = matrix[0][0]
for first row
sum[0][j] = sum[0][j-1] + matrix[0][j]
for first column
sum[i][0] = sum[i-1][0] + matrix[i][0]
for all other rows and columns
sum[i][j] = matrix[i][j] + sum[i-1][j] + sum[i][j-1] – sum[i-1][j-1]


// a is input array .. filled with sample inputs
int a[][] = {
{1,1,1,1,1},
{2,2,2,2,2},
{3,3,3,3,3},
{4,4,4,4,4},
{5,5,5,5,5}
};
int sum[][] = new int[a.length][a[0].length];
sum[0][0] = a[0][0];
for(int i=1;i<a.length;i++){
sum[i][0] = sum[i-1][0] + a[i][0];
}
for(int j=1;j<a[0].length;j++){
sum[0][j] = sum[0][j-1] + a[0][j];
}
for(int i=1; i<a.length;i++) {
for(int j=1; j<a[0].length;j++) {
sum[i][j] = a[i][j]
+ sum[i][j-1]
+ sum[i-1][j]
- sum[i-1][j-1];
}
}

]]>
By: umar /2011/09/20/programming-interview-questions-2-matrix-region-sum/#comment-755 umar Wed, 14 Dec 2011 08:21:16 +0000 /?p=478#comment-755 Good Solution. I have seen your some posts. Very Good questions. Please write code in C++ also. Because some time understand is difficult. Thanks Good Solution.
I have seen your some posts. Very Good questions.
Please write code in C++ also.
Because some time understand is difficult.

Thanks

]]>