当前位置:网站首页>LeetCode 785:判断二分图
LeetCode 785:判断二分图
2022-06-27 01:49:00 【斯沃福德】
思路:
判定二分图的算法很简单,就是用代码解决「双色问题」。
说白了就是遍历一遍图,一边遍历一边染色,看看能不能用两种颜色给所有节点染色,且相邻节点的颜色都不相同。
class Solution {
boolean a=true;
boolean[] marked;
boolean[] color;
public boolean isBipartite(int[][] graph) {
int n=graph.length;
marked=new boolean[n];
color=new boolean[n]; // 自动初始化为全false;
//遍历每个顶点
for(int i=0;i<n;i++){
dfs(graph,i);
}
return a;
}
void dfs(int[][] graph,int s){
//终止条件:不是二分数则无需再递归
if(!a){
return;
}
marked[s]=true;
//遍历邻接表
for(int k:graph[s]){
if(!marked[k]){
//节点未访问过
//上色 !
color[k]=!color[s]; // s 和k相邻! 所以上不同的色!
dfs(graph,k);
}//节点已被访问过
if(color[k]==color[s]){
// 相邻的s和v颜色相同则不是二分图
a=false;
}
}
}
}
边栏推荐
猜你喜欢

Learn the most basic operation of discodiffusion

Don't be brainwashed. This is the truth about the wages of 90% of Chinese people

速看!2022年6月编程语言排行榜出炉!第一名太牛啦

Detailed explanation of ThreadLocal

Parameter estimation -- Chapter 7 study report of probability theory and mathematical statistics (point estimation)

“所有专业都在劝退”,对大学生最友好的竟然是它?

简单学习GoogleColab的入门级概念

Bs-gx-016 implementation of textbook management system based on SSM

SystemVerilog仿真速率提升

Installing the Damon database using the command line
随机推荐
Summer planning for the long river
George Washington University: Hanhan Zhou | PAC: auxiliary value factor decomposition with counterfactual prediction in Multi-Agent Reinforcement Learning
学习DiscoDiffusion的最基础操作
Some exception handling for idea plug-in development
memcached基础11
idea 插件开发一些异常处理
SQLite Reader 插件测试SQLite语法
markdown表格(合并)
get_ Usage Summary of sequencer
Hot discussion: what are you doing for a meaningless job with a monthly salary of 18000?
memcached基础14
I encountered some problems when connecting to the database. How can I solve them?
memcached基礎12
速看!2022年6月编程语言排行榜出炉!第一名太牛啦
Continuous delivery blue ocean application
Pointer compression for JVM
Memcached foundation 10
Memcached basics 13
Ymal文件的增删改查
Detailed explanation of ThreadLocal