Advertisement
bl00dt3ars

test

Jun 7th, 2021
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import numpy as np
  2.  
  3. maxRow = 500
  4. maxCol = 500
  5.  
  6. visited = np.zeros((maxCol, maxRow))
  7.  
  8. # Function that return true if mat[row][col]
  9. # is valid and hasn't been visited
  10. def isSafe(M, row, col, c, n, l) :
  11.  
  12.     # If row and column are valid and element
  13.     # is matched and hasn't been visited then
  14.     # the cell is safe
  15.     return ((row >= 0 and row < n) and
  16.             (col >= 0 and col < l) and
  17.             (M[row][col] == c and not
  18.             visited[row][col]));
  19.  
  20. # Function for depth first search
  21. def DFS(M, row, col, c, n, l) :
  22.  
  23.     # These arrays are used to get row
  24.     # and column numbers of 4 neighbours
  25.     # of a given cell
  26.     rowNbr = [ -1, 1, 0, 0 ];
  27.     colNbr = [ 0, 0, 1, -1 ];
  28.  
  29.     # Mark this cell as visited
  30.     visited[row][col] = True;
  31.  
  32.     # Recur for all connected neighbours
  33.     for k in range(4) :
  34.         if (isSafe(M, row + rowNbr[k],
  35.                 col + colNbr[k], c, n, l)) :
  36.  
  37.             DFS(M, row + rowNbr[k],
  38.                 col + colNbr[k], c, n, l);
  39.  
  40. # Function to return the number of
  41. # connectewd components in the matrix
  42. def connectedComponents(M, n) :
  43.  
  44.     connectedComp = 0;
  45.     l = len(M[0]);
  46.  
  47.     for i in range(n) :
  48.         for j in range(l) :
  49.             if (not visited[i][j]) :
  50.                 c = M[i][j];
  51.                 DFS(M, i, j, c, n, l);
  52.                 connectedComp += 1;
  53.  
  54.     return connectedComp;
  55.  
  56. # Driver code
  57. if __name__ == "__main__" :
  58.  
  59.     M = ["aabba", "aabba", "aaaca"];
  60.     n = len(M)
  61.  
  62.     print(connectedComponents(M, n));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement