Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- maxRow = 500
- maxCol = 500
- visited = np.zeros((maxCol, maxRow))
- # Function that return true if mat[row][col]
- # is valid and hasn't been visited
- def isSafe(M, row, col, c, n, l) :
- # If row and column are valid and element
- # is matched and hasn't been visited then
- # the cell is safe
- return ((row >= 0 and row < n) and
- (col >= 0 and col < l) and
- (M[row][col] == c and not
- visited[row][col]));
- # Function for depth first search
- def DFS(M, row, col, c, n, l) :
- # These arrays are used to get row
- # and column numbers of 4 neighbours
- # of a given cell
- rowNbr = [ -1, 1, 0, 0 ];
- colNbr = [ 0, 0, 1, -1 ];
- # Mark this cell as visited
- visited[row][col] = True;
- # Recur for all connected neighbours
- for k in range(4) :
- if (isSafe(M, row + rowNbr[k],
- col + colNbr[k], c, n, l)) :
- DFS(M, row + rowNbr[k],
- col + colNbr[k], c, n, l);
- # Function to return the number of
- # connectewd components in the matrix
- def connectedComponents(M, n) :
- connectedComp = 0;
- l = len(M[0]);
- for i in range(n) :
- for j in range(l) :
- if (not visited[i][j]) :
- c = M[i][j];
- DFS(M, i, j, c, n, l);
- connectedComp += 1;
- return connectedComp;
- # Driver code
- if __name__ == "__main__" :
- M = ["aabba", "aabba", "aaaca"];
- n = len(M)
- print(connectedComponents(M, n));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement