看到这个题好想哭啊 fb面的这个
我是想到了count island那个题 用了dfs 一开始应该是死循环了? 溢出 然后看答案是假如这个点没有更新 那从它开始的四周也就没必要再更新了 没想清楚 这样的话感觉是mn的时间复杂度
public class Solution {
public void wallsAndGates(int[][] rooms) {
if ( rooms == null )
return;
for ( int i = 0; i < rooms.length; i ++ ){
for ( int j = 0; j < rooms[ 0 ].length; j ++ ){
if ( rooms [ i ][ j ] == 0 ){
mark ( rooms, 0, i, j );
}
}
}
}
public void mark ( int [][] rooms, int val, int m, int n ){
if ( m < 0 || m >= rooms.length || n < 0 || n >= rooms[0].length || rooms[ m ][ n ] == -1 )
return;
if ( rooms[ m ][ n ] >= val ){
rooms [ m ][ n ] = val;
mark ( rooms, val + 1, m + 1, n );
mark ( rooms, val + 1, m, n + 1 );
mark ( rooms, val + 1, m - 1, n );
mark ( rooms, val + 1, m, n - 1 );
}
}
}
bfs o(mn)的 首先把所有的0入队 然后每次拿出一个 假如四个邻居有还是inf的就更新并且入队
每个格子只入队一次 每次是离0距离相等的一层 所以距离是每层增加的 只要这个格子不是inf了 就是最小距离了 不用再更新
public class Solution {
public void wallsAndGates(int[][] rooms) {
if ( rooms == null )
return;
Queue<int[]> que = new LinkedList<int[]>();
for ( int i = 0; i < rooms.length; i ++ ){
for ( int j = 0; j < rooms[ 0 ].length; j ++ ){
if ( rooms[ i ][ j ] == 0 ){
int [] pos = new int [ 2 ];
pos [ 0 ] = i;
pos [ 1 ] = j;
que.offer ( pos );
}
}
}
while ( !que.isEmpty() ){
int [] po = que.poll();
int m = po [ 0 ];
int n = po [ 1 ];
if ( m > 0 && rooms [ m - 1 ][ n ] == Integer.MAX_VALUE ){
rooms [ m - 1] [ n ] = rooms [ m ][ n ] + 1;
int [] pos = new int [ 2 ];
pos [ 0 ] = m - 1;
pos [ 1 ] = n;
que.offer ( pos );
}
if ( n > 0 && rooms [ m ][ n - 1 ] == Integer.MAX_VALUE ){
rooms [ m ] [ n - 1 ] = rooms [ m ][ n ] + 1;
int [] pos = new int [ 2 ];
pos [ 0 ] = m;
pos [ 1 ] = n - 1;
que.offer ( pos );
}
if ( m < rooms.length - 1 && rooms [ m + 1 ][ n ] == Integer.MAX_VALUE ){
rooms [ m + 1] [ n ] = rooms [ m ][ n ] + 1;
int [] pos = new int [ 2 ];
pos [ 0 ] = m + 1;
pos [ 1 ] = n;
que.offer ( pos );
}
if ( n < rooms[0].length - 1 && rooms [ m ][ n + 1 ] == Integer.MAX_VALUE ){
rooms [ m ] [ n + 1 ] = rooms [ m ][ n ] + 1;
int [] pos = new int [ 2 ];
pos [ 0 ] = m;
pos [ 1 ] = n + 1;
que.offer ( pos );
}
}
}
}