简体   繁体   English

如何将二维矩阵作为参数传递给函数?

[英]How to pass a 2-d matrix as an argument to function?

There is a problem on leetcode and for C language we have to implement a function with definition as leetcode 有问题,对于 C 语言,我们必须实现一个定义为的函数

int numIslands(char** grid, int gridRowSize, int *gridColSizes);

I can not change the definition of this function.无法更改此函数的定义。

I have implemented it as我已将其实现为

#define VISITED 'v'

void dfs(char** grid, int gridRowSize,
         int gridColSizes, int i, int j) {
    grid[i][j] = VISITED; <- throws


    if (i - 1 >= 0 && grid[i - 1][j] == '1') <- throws
        dfs(grid, gridRowSize, gridColSizes, i - 1, j);

    if (i + 1 < gridRowSize && grid[i + 1][j] == '1')
        dfs(grid, gridRowSize, gridColSizes, i + 1, j);

    if (j - 1 >= 0 && grid[i][j - 1] == '1')
        dfs(grid, gridRowSize, gridColSizes, i, j - 1);

    if (j + 1 < gridColSizes && grid[i][j + 1] == '1')
        dfs(grid, gridRowSize, gridColSizes, i, j + 1);
}

int numIslands(char **grid, int gridRowSize, int *gridColSizes) {
    int count = 0;

    for (int i = 0; i < gridRowSize; i++) {
        for (int j = 0; j < *gridColSizes; j++) {
            if (grid[i][j] == '1') {
                count++;
                dfs(grid, gridRowSize, *gridColSizes, i, j);
            }
        }
    }

    return count;
}

int main() {
    char **grid = {
            {'1','1','1','1','0'},
            {'1','1','0','1','0'},
            {'1','1','0','0','0'},
            {'0','0','0','0','0'}
    };
    int cols = 5;

    int res = numIslands(grid, 4, &cols);
}

It compiles, but throws on lines with indexed access to grid (like mentioned lines in code).它编译,但抛出对网格进行索引访问的行(如代码中提到的行)。

You might do:你可能会这样做:

char line1[] = {'1', '1', '1', '1', '0'};
char line2[] = {'1', '1', '0', '1', '0'};
char line3[] = {'1', '1', '0', '0', '0'};
char line4[] = {'0', '0', '0', '0', '0'};
int sizes[] = {
    sizeof(line1) / sizeof(*line1),
    sizeof(line2) / sizeof(*line2),
    sizeof(line3) / sizeof(*line3),
    sizeof(line4) / sizeof(*line4)
};
char* grid[] = {line1, line2, line3, line4};
int gridRowSize = sizeof(grid) / sizeof(*grid);

int res = numIslands(grid, gridRowSize, lines);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM