#include #include using namespace std; int dr[] = {-1, 1, 0, 0, -1, -1, 1, 1}; int dc[] = {0, 0, -1, 1, -1, 1, -1, 1}; bool is_valid_move(const vector>& matrix, vector>& visited, int row, int col, int N) { return (row >= 0 && row < N && col >= 0 && col < N && matrix[row][col] == 1 && !visited[row][col]); } void DFS(const vector>& matrix, vector>& visited, int row, int col, int N) { visited[row][col] = true; for (int i = 0; i < 8; i++) { int new_row = row + dr[i]; int new_col = col + dc[i]; if (is_valid_move(matrix, visited, new_row, new_col, N)) { DFS(matrix, visited, new_row, new_col, N); } } } int count_connected_components(const vector>& matrix) { int N = matrix.size(); vector> visited(N, vector(N, false)); int count = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (matrix[i][j] == 1 && !visited[i][j]) { count++; DFS(matrix, visited, i, j, N); } } } return count; } int main() { vector> matrix = { {1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0}, {1, 1, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 0} }; int result = count_connected_components(matrix); cout << "The number of connected components is " << result << endl; return 0; }