DFS & BFS:

关键在于构造graph

 package twoSigma;

 import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue; public class FriendCircle1 {
ArrayList<ArrayList<Integer>> graph;
public int friendCircles(String[] friends) {
graph = new ArrayList<ArrayList<Integer>>();
for (int i=0; i<friends.length; i++) {
ArrayList<Integer> item = new ArrayList<Integer>();
for (int j=0; j<friends[0].length(); j++) {
if (i!=j && friends[i].charAt(j) == 'Y') {
item.add(j);
}
}
graph.add(new ArrayList<Integer>(item));
}
HashSet<Integer> visited = new HashSet<Integer>();
int res = 0;
for (int i=0; i<graph.size(); i++) {
if (!visited.contains(i)) {
res++;
//bfs(i, visited);
dfs(i, visited);
}
}
return res;
} public void bfs(int i, HashSet<Integer> visited) {
visited.add(i);
Queue<Integer> q = new LinkedList<Integer>();
q.offer(i);
while (!q.isEmpty()) {
int cur = q.poll();
ArrayList<Integer> curFriends = graph.get(cur);
for (int each : curFriends) {
if (!visited.contains(each)) {
visited.add(each);
q.offer(each);
}
}
}
} public void dfs(int i, HashSet<Integer> visited) {
if (visited.contains(i)) return;
visited.add(i);
ArrayList<Integer> friends = graph.get(i);
for (int friend : friends) {
dfs(friend, visited);
}
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FriendCircle1 sol = new FriendCircle1();
//String[] input = new String[]{"YNYNNN", "NYNYNN", "YNYNNN", "NYNYNN", "NNNNYY", "NNNNYY"};
//String[] input = new String[]{"YYNN", "YYYN", "NYYN", "NNNY"};
//String[] input = new String[]{"YNN", "NYN", "NNY"};
String[] input = new String[]{"YYY", "YYY", "YYY"};
int count = sol.friendCircles(input);
System.out.println(count);
} }

如果想把String[] array转化为2d char array, code如下,写的时候这里出了点小问题。friends是String[]

         char[][] arr = new char[friends.length][];
for (int i=0; i<friends.length; i++) {
arr[i] = friends[i].toCharArray();
}

Union Find

 package twoSigma;

 public class FriendCircle2 {
public int friendCircles(String[] friends) {
Unionfind uf = new Unionfind(friends.length);
for (int i=0; i<friends.length; i++) {
for (int j=0; j<friends[i].length(); j++) {
if (i != j && friends[i].charAt(j)=='Y')
uf.union(i, j);
}
}
return uf.count;
} public class Unionfind {
int[] ids;
int count;
public Unionfind(int num) {
this.ids = new int[num];
this.count = num;
for (int i=0; i<num; i++) {
ids[i] = i;
}
} public int findId(int i) {
return ids[i];
} public boolean isConnected(int i1, int i2) {
return findId(i1)==findId(i2);
} public boolean union(int i1, int i2) {
if (!isConnected(i1, i2)) {
for (int i=0; i<ids.length; i++) {
if (ids[i] == findId(i2)) {
ids[i] = findId(i1);
}
}
count--;
return true;
}
return false;
}
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FriendCircle2 sol = new FriendCircle2();
String[] input = new String[]{"YNYNNN", "NYNYNN", "YNYNNN", "NYNYNN", "NNNNYY", "NNNNYY"};
//String[] input = new String[]{"YYNN", "YYYN", "NYYN", "NNNY"};
//String[] input = new String[]{"YNN", "NYN", "NNY"};
//String[] input = new String[]{"YYY", "YYY", "YYY"};
int count = sol.friendCircles(input);
System.out.println(count);
} }

2Sigma OA prepare: Friends Circle的更多相关文章

  1. 2Sigma OA prepare: Longest Chain

    DP use HashMap: 根据string的长度sort,然后维护每个string的longest chain,default为1,如果删除某个char生成的string能提供更长的chain, ...

  2. Twitter OA prepare: Two Operations

    准备T家OA,网上看的面经 最直接的方法,从target降到1,如果是奇数就减一,偶数就除2 public static void main(String[] args) { int a = shor ...

  3. Twitter OA prepare: even sum pairs

    思路:无非就是扫描一遍记录奇数和偶数各自的个数,比如为M和N,然后就是奇数里面选两个.偶数里面选两个,答案就是M(M-1)/2 + N(N-1)/2

  4. Twitter OA prepare: K-complementary pair

    2sum的夹逼算法,需要sort一下.本身不难,但是tricky的地方在于允许同一个数组元素自己跟自己组成一个pair,比如上例中的[5, 5].而且数组本身就允许值相等的元素存在,在计算pair时, ...

  5. Twitter OA prepare: Anagram is A Palindrome

    Algorithm: Count the number of occurrence of each character. Only one character with odd occurrence ...

  6. Twitter OA prepare: Visit element of the array

    分析:就是建立一个boolean array来记录array里面每个元素的访问情况,遇到访问过的元素就停止visiting,返回未访问的结点个数 public int visiting(int[] A ...

  7. Twitter OA prepare: Rational Sum

    In mathematics, a rational number is any number that can be expressed in the form of a fraction p/q ...

  8. Twitter OA prepare: Flipping a bit

    You are given a binary array with N elements: d[0], d[1], ... d[N - 1]. You can perform AT MOST one ...

  9. Twitter OA prepare: Equilibrium index of an array

    Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to ...

随机推荐

  1. 【BZOJ】3093: [Fdu校赛2012] A Famous Game

    http://www.lydsy.com/JudgeOnline/problem.php?id=3093 题意:n个球(红和蓝两种),等概率有1~n个红球.首先取出p个球且这p个球里边有q个红球,问从 ...

  2. 【BZOJ1051】1051: [HAOI2006]受欢迎的牛 tarjan求强连通分量+缩点

    Description 每一头牛的愿望就是变成一头最受欢迎的牛.现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎. 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认 ...

  3. 清空highcharts数据

    1:清空highcharts图表的数据我们常用的方法就是remove() var seriesList = chart.series; //获得图表的所有序列 var seriesCount=seri ...

  4. c# winform 全角自动转化半角问题(C#中ImeMode的值):转载

    调用 this.ImeMode = ImeMode.OnHalf; ImeMode 枚举:指定一个值,该值是用来确定在选定了对象时该对象的输入法编辑器 (IME) 的状态. 以下是微软的解释: 成员名 ...

  5. MAT(Memory Analyzer Tool)工具入门介绍

    1.MAT是什么? MAT(Memory Analyzer Tool),一个基于Eclipse的内存分析工具,是一个快速.功能丰富的JAVA heap分析工具,它可以帮助我们查找内存泄漏和减少内存消耗 ...

  6. ECMAScript中关于如何获取this的定义

    文章中一些名词的翻译存疑,没有查过正式的中文名称 前面都是具体过程的解释,懒得看可以直接看获取思路 有关this的取值请移步JavaScript笔记--this的取值 获取this的过程 Runtim ...

  7. Qt 控件随窗口缩放

    在Qt的界面设计中,我们有时候希望窗口在最大化的时候,上面的控件也跟着缩放,那么我们就需要调整控件的SizePolicy属性,关于这个属性的讲解请参见我之前的博客Qt SizePolicy 属性,由于 ...

  8. mvn install

    mvn install:install-file \ -DgroupId=com.weibo.datasys.weistreamng \ -DartifactId=weistreamng-092-fr ...

  9. poj1700

    这题的最坑的地方就是每步可能会有两种情况,这两情况起初我都单独考虑了,但就是没放在一起考虑...wa个不停,果然贪心是一个很考验思维的东西. 这里可以这样考虑,在运人的过程中,河的起始岸最后终将剩下一 ...

  10. 示例Oracle 10.2.0.1.0升级到10.2.0.4.0一例

    1.查看当前系统版本 [oracle@std Disk1]$ sqlplus '/as sysdba' SQL*Plus: Release - Production on Thu Jan :: Cop ...