Works fine as custom input but fails on Submit/Test


#1

Here’s my code:

void dfs(vector<vector<int>>& A, vector<vector<bool>>& visited, int i, int j, int* size) {
    int rows = A.size(), cols = A[0].size();
    (*size)++;
    visited[i][j] = true;
    if (i>0 && !visited[i-1][j] && A[i-1][j] == 1) dfs(A, visited, i-1, j, size);
    if (i>0 && j < cols && !visited[i-1][j+1] && A[i-1][j+1] == 1) dfs(A, visited, i-1, j+1, size);
    if (j < cols && !visited[i][j+1] && A[i][j+1] == 1) dfs(A, visited, i, j+1, size);
    if (i<rows-1 && j < cols && !visited[i+1][j+1] && A[i+1][j+1] == 1) dfs(A, visited, i+1, j+1, size);
    if (i<rows-1 && !visited[i+1][j] && A[i+1][j] == 1) dfs(A, visited, i+1, j, size);
    if (i<rows-1 && j > 0 && !visited[i+1][j-1] && A[i+1][j-1] == 1) dfs(A, visited, i+1, j-1, size);
    if (j>0 && !visited[i][j-1] && A[i][j-1] == 1) dfs(A, visited, i, j-1, size);
    if (i>0 && j > 0 && !visited[i-1][j-1] && A[i-1][j-1] == 1) dfs(A, visited, i-1, j-1, size);
}

int Solution::solve(vector<vector<int> > &A) {
    int rows = A.size(), cols = A[0].size();
    vector<vector<bool>> visited(rows, vector(cols, false));
    int largest = -100;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j< cols; j++) {
            if (!visited[i][j] && A[i][j] == 1) {
                int tempLarge = 0;
                dfs(A, visited, i, j, &tempLarge);
                largest = max(largest, tempLarge);
            }
        }
    }

    return largest;
}

For this test case:

[
  [0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0]
  [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0]
  [1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0]
  [0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1]
  [0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0]
  [0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1]
  [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0]
  [1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1]
  [1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1]
  [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1]
  [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1]
  [1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1]
  [1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0]
]

It runs fine on RUN AS CUSTOM INPUT but fails for Submit/Test. Can someone from interviewbit team check this ?