How to create a B[n][n] matrix (2 ≤ n ≤100) from the matrix A[n][n] ? . In which B[i][j] element is equal to the maximum element of the matrix A , which is bounded on the right by the diagonal passing on A[i][j] . The task was translated as closely as possible, but the essence is not completely clear. Help Wanted.

|
1 answer
See - we work in columns. Then the first column B simply equal to the first column A
Further, in each subsequent column B for the element B[i][j] it is necessary to consider the elements B[i-1][j-1] , B[i][j-1] , B[i+1][j-1] and A[i][j] and select the maximum one.
It is written very simply :)
In my opinion, so . (c) Pooh
Something like this (wrote almost in C, not C ++, and for constant size):
#include <cstdlib> #include <cstdio> #include <climits> using namespace std; const int N = 4; int A[N][N]; int B[N][N]; inline int get(int X[N][N], int r, int c) { if (r<0 || r>=N || c<0 || c >=N) return INT_MIN; return X[r][c]; } int main(int argc, const char * argv[]) { for(int i = 0; i < N; ++i) { for(int j = 0; j < N; ++j) { A[i][j] = rand()%100; printf("%4d",A[i][j]); } printf("\n"); } printf("\n\n"); for(int c = 0; c < N; ++c) { for(int r = 0; r < N; ++r) { int v0 = get(B,r-1,c-1); int v1 = get(B,r, c-1); int v2 = get(B,r+1,c-1); int v3 = get(A,r ,c ); v0 = (v0 > v1) ? v0 : v1; v2 = (v2 > v3) ? v2 : v3; B[r][c] = (v0 > v2) ? v0 : v2; } } for(int i = 0; i < N; ++i) { for(int j = 0; j < N; ++j) { printf("%4d",B[i][j]); } printf("\n"); } printf("\n\n"); } I think, figure it out yourself. Comments on what does what line of code - will not ...
- Why is the first column B equal to A? - netrox
- Yes, because you have a diagonal cut-off select only one element ... - Harry
- And what is INT_MIN? - netrox
- Roughly - an analogue of minus infinity for missing cells (for example, when we look at the very top or left ...) - so as not to process their absence, we replace them with fictitious ones with an obviously undesirable value. - Harry
|