Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
759 B
1
Indexable
// Dimensions of the grid
int rows, cols;

// Function to check if a cell is inside the grid and has a value of 1
bool isSafe(int x, int y, vector<vector<int>>& grid, vector<vector<bool>>& visited) {
    return (x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] && !visited[x][y]);
}

// DFS function to mark a house's cells
void DFS(int x, int y, vector<vector<int>>& grid, vector<vector<bool>>& visited) {
    // Directions for adjacent cells
    int dx[] = {-1, 0, 1, 0};
    int dy[] = {0, 1, 0, -1};
    
    visited[x][y] = true;
    
    // Traverse all adjacent cells
    for (int dir = 0; dir < 4; dir++) {
        if (isSafe(x + dx[dir], y + dy[dir], grid, visited)) {
            DFS(x + dx[dir], y + dy[dir], grid, visited);
        }
    }
}