Could you please explain why the zero case failed?


  • 0
    B
    char v[256][256];
    char g[256][256];
    
    void dfs(int numRows, int numColumns, int i, int j) {
        v[i][j] = 1;
        if (i > 0 && '1' == g[i-1][j] && 0 == v[i-1][j])
            dfs(numRows, numColumns, i - 1, j);
        if (j > 0 && '1' == g[i][j-1] && 0 == v[i][j-1])
            dfs(numRows, numColumns, i, j - 1);
        if (i + 1 < numRows && '1' == g[i+1][j] && 0 == v[i+1][j])
            dfs(numRows, numColumns, i, j - 1);
        if (j + 1 < numColumns && '1' == g[i][j+1] && 0 == v[i][j+1])
            dfs(numRows, numColumns, i, j + 1);
    }
    
    int numIslands(char **grid, int numRows, int numColumns) {
        int i, j, ans = 0;
        
        memset(v, 0, sizeof(v));
        memset(g, 0, sizeof(g));
        for (i = 0; i < numRows; i++)
            for (j = 0; j < numColumns; j++)
                g[i][j] = *((char*)grid + i * numColumns + j);
    
        for (i = 0; i < numRows; i++) {
            for (j = 0; j < numColumns; j++) {
                if (1 == v[i][j] || '0' == g[i][j])
                    continue;
                ans++;
                dfs(numRows, numColumns, i, j);
            }
        }
    
        return ans;
    }
    
    ============================
    
    Input:	["0"]
    Output:	1
    Expected:	0

  • 0
    Y
    void dfs(int numRows, int numColumns, int i, int j) {
    v[i][j] = 1;
    if (i > 0 && '1' == g[i-1][j] && 0 == v[i-1][j])
        dfs(numRows, numColumns, i - 1, j);
    if (j > 0 && '1' == g[i][j-1] && 0 == v[i][j-1])
        dfs(numRows, numColumns, i, j - 1);
    if (i + 1 < numRows && '1' == g[i+1][j] && 0 == v[i+1][j])
    

    /* maybe this line should be: dfs(numRows, numColumns, i+1, j );*/
    dfs(numRows, numColumns, i, j - 1);
    if (j + 1 < numColumns && '1' == g[i][j+1] && 0 == v[i][j+1])
    dfs(numRows, numColumns, i, j + 1);
    }``


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.