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

时间:2019-04-12 18:10:41

标签: c

a problem on leetcode,对于C语言,我们必须实现定义为的函数

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

无法更改此功能的定义。

我已将其实现为

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

它可以编译,但是会抛出对网格具有索引访问权限的行(如代码中提到的行)。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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);