Advertisement
bai_onzi

smallWorld.js

Jun 29th, 2023
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let [N, M] = gets().split(' ').map(Number);
  2. let matrix = Array.from({ length: N }, () => gets().split('').map(Number));
  3. let visited = Array.from({ length: N }, () => Array(M).fill(false));
  4.  
  5. let result = [];
  6.  
  7. // console.log(N, M, matrix, visited)
  8.  
  9. const dfs = (row, col) => {
  10.     if(row < 0 || row >= N || col < 0 || col >= M || visited[row][col] || matrix[row][col] !== 1){
  11.         return 0;
  12.     }
  13.  
  14.     visited[row][col] = true;
  15.  
  16.     let size = 1;
  17.  
  18.     size += dfs(row - 1, col); // up
  19.     size += dfs(row + 1, col); // down
  20.     size += dfs(row, col - 1); // left
  21.     size += dfs(row, col + 1); // right
  22.  
  23.     return size;
  24. }
  25.  
  26. for(let i = 0; i < N; i++){
  27.     for(let j = 0; j < M; j++){
  28.         if(matrix[i][j] === 1 && !visited[i][j]){
  29.             const size = dfs(i, j);
  30.             result.push(size);
  31.         }
  32.     }
  33. }
  34. result.sort((a, b) => b - a);
  35. for(let size of result){
  36.     console.log(size)
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement