畅游图论之判断二分图
方法1:BFS
public boolean isBipartite ( int [ ] [ ] graph) {
int V = graph. length;
int [ ] colors = new int [ V ] ;
Arrays . fill ( colors, - 1 ) ;
Queue < Integer > queue = new LinkedList < > ( ) ;
for ( int i = 0 ; i < V ; i++ ) {
if ( colors[ i] == - 1 ) {
queue. offer ( i) ;
colors[ i] = 0 ;
while ( ! queue. isEmpty ( ) ) {
int u = queue. poll ( ) ;
for ( int v : graph[ u] ) {
if ( colors[ v] == colors[ u] ) return false ;
if ( colors[ v] == - 1 ) {
colors[ v] = 1 - colors[ u] ;
queue. offer ( v) ;
}
}
}
}
}
return true ;
}
另外一种写法
public boolean isBipartite ( int [ ] [ ] graph) {
int V = graph. length;
int [ ] colors = new int [ V ] ;
Queue < Integer > queue = new LinkedList < > ( ) ;
for ( int i = 0 ; i < V ; i++ ) {
if ( colors[ i] == 0 ) {
queue. offer ( i) ;
colors[ i] = 1 ;
while ( ! queue. isEmpty ( ) ) {
int u = queue. poll ( ) ;
for ( int v : graph[ u] ) {
if ( colors[ v] == colors[ u] ) return false ;
if ( colors[ v] == 0 ) {
colors[ v] = - colors[ u] ;
queue. offer ( v) ;
}
}
}
}
}
return true ;
}
方法2:DFS
public boolean isBipartite ( int [ ] [ ] graph) {
int V = graph. length;
int [ ] colors = new int [ V ] ;
for ( int i = 0 ; i < V ; i++ ) {
if ( colors[ i] == 0 && ! helper ( graph, colors, i, 1 ) ) return false ;
}
return true ;
}
private boolean helper ( int [ ] [ ] graph, int [ ] colors, int u, int c) {
if ( colors[ u] != 0 ) {
return colors[ u] == c;
}
colors[ u] = c;
for ( int v : graph[ u] ) {
if ( ! helper ( graph, colors, v, - c) ) return false ;
}
return true ;
}
Reference