1

我试图找到 2d 矩阵的鞍点并使用指针返回矩阵,但我的代码没有按预期执行。

这是我的代码

#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;
}

在此处输入图像描述

这张图片显示了输入(3x3 矩阵),输出应该是空白而不是 8,因为矩阵中没有鞍点。我不确定我的代码有什么问题

编辑:我遇到了一个新问题。其中一个测试用例的输入为:

(3x4) 矩阵,在右侧的最后一列中有一个无关的-1-5

输入:

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

输出:-2

预期输出应该是0.

在此测试用例中,-1-5是超出列数的额外输入。它们应该被视为空值,但在这种情况下它们不是。

4

1 回答 1

1

这里有两个错误:

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

您的意思是<而不是>,并且忘记存储列索引;正确的:

      if (*(p[i] + j) < small)    // or simply if (a[i][j] < small)
      {   smallcol = j,
于 2021-11-06T23:26:57.980 回答