human
What is a code to maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix and the other steps required given the following:
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Function to find the maximum distance.
Queue to store all 1 - cells.
Grid dimensions.
Directions traversable from a given a particular cell.
If the grid contains only 0 s or only 1 s.
Access every 1 - cell.
Traverse all possible directions from the cells.
Check if the cell is within the boundaries or contains a 1.
Driver code"
How can the above be solved in Python?
assistant
#Here is code to maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix and the other steps required.
 def maxDistance ( grid ) :
	q = [ ]
	M = len ( grid )
	N = len ( grid [ 0 ] )
	ans = - 1
	dirs = [ [ 0 , 1 ] , [ 1 , 0 ] , [ 0 , - 1 ] , [ - 1 , 0 ] ]
	for i in range ( M ) :
		for j in range ( N ) :
			if ( grid [ i ] [ j ] == 1 ) :
				q . append ( [ i , j ] )
	if ( len ( q ) == 0 or M * N == len ( q ) ) :
		return - 1
	while ( len ( q ) > 0 ) :
		cnt = len ( q )
		while ( cnt > 0 ) :
			p = q [ 0 ]
			q . pop ( )
			for Dir in dirs :
				x = p [ 0 ] + Dir [ 0 ]
				y = p [ 1 ] + Dir [ 1 ]
				if ( x < 0 or x >= M or y < 0 or y >= N or grid [ x ] [ y ] ) :
					continue
				q . append ( [ x , y ] )
				grid [ x ] [ y ] = 1
			cnt -= 1
		ans += 2
	return ans
arr = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] ]
print ( maxDistance ( arr ) )