Steven Yelnats
Steven Yelnats

Reputation: 21

finding saddle point in 2d matrix

I’m trying to find the saddle point of a 2d Matrix and refer back to the Matrix by using a pointer, but my code isn’t executing as intended.

here is my code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, m, i, j;
    int small, smallcol, large, largerow;

    scanf("%d%d", &n, &m);  // n is row, m is column
    int a[n][m];
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    int* p[n];

    for (i = 0; i < n; i++)
    {
        p[i] = a[i];
    }

    for (i = 0; i < n; i++)
    {
        small = *p[I];
        smallcol = 0;
        ;
        for (j = 1; j < m; j++)
        {
            if (*(p[i] + j) > small)
            {
                small = *(p[i] + j);
            }
        }
        large = *(p[0] + smallcol);
        largerow = 0;
        for (j = 1; j < n; j++)
        {
            if (*(p[j] + smallcol) > large)
            {
                large = *(p[j] + smallcol);
                largerow = j;
            }
        }

        if (i == largerow)
        {
            printf("%d", *(p[i] + smallcol));
        }
        if (i != largerow)
        {
            printf(" ");
        }
    }

    return 0;
}

enter image description here

this picture shows the input (3x3 matrix) and the output should have been blank instead of 8 since there is no saddle point in the matrix. I'm not sure what the problem with my code is

Edit: I ran into a new problem. One of the test cases has the input as:

(3x4) matrix, with an extraneous -1 and -5 in the last column on the right:

Input:

-1 -2 -1  3 -1
-3 -5  2  3 -5
 0  0  0  1

Output: -2

Expected output should be 0.

In this test case, the -1 and -5 are extra inputs that exceed the number of columns. They should be considered as null, but in this case they aren’t.

Upvotes: 1

Views: 208

Answers (1)

Armali
Armali

Reputation: 19395

Two errors are here:

      if (*(p[i] + j) > small)
        {

You meant < rather than >, and forgot to store the column index; correct:

      if (*(p[i] + j) < small)    // or simply if (a[i][j] < small)
      {   smallcol = j,

Upvotes: 1

Related Questions