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. FLEX SharedObject介绍及应用

    ShareObject介绍: 1 ShareObject,顾名思义共享对象,而通常意义上的共享,从B/S结构上来讲,无非是客户端(浏览器端)的共享和服务器端的共享了,不错,ShareObject刚好份 ...

  2. VS2010 C++环境下DLL和LIB文件目录及名称修改

    VS2010 C++环境下DLL和LIB文件目录及名称修改 转自:http://blog.csdn.net/archielau/article/details/8507581 DLL工程,Debug版 ...

  3. Connect模块解析

    Connect模块背景 Node.js的愿望是成为一个能构建高速,可伸缩的网络应用的平台,它本身具有基于事件,异步,非阻塞,回调等特性,这在前几篇专栏中有过描述. 正是基于这样的一些特性,Node.j ...

  4. #define is unsafe——I

    I. #define is unsafe Have you used #define in C/C++ code like the code below? #include <stdio.h&g ...

  5. [LintCode] Maximal Square 最大正方形

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and ret ...

  6. spring security 控制用户信息用户加密 缓存用户信息

    1. MD5加密 任何一个正式的企业应用中,都不会在数据库中使用明文来保存密码的,我们在之前的章节中都是为了方便起见没有对数据库中的用户密码进行加密,这在实际应用中是极为幼稚的做法.可以想象一下,只要 ...

  7. 模拟状态为inactive的日志损坏的恢复实验(完全恢复)

    1查看当前日志状态 从这里可以看到我们现在有三组日志,每组日志中只有1个成员.为了演示这个实验,我们为每个组增加1个成员. 2为每组增加组成员 添加后我们验证一下目前各日志成员的状态: 从上面的视图中 ...

  8. 【HDU4419 Colourful Rectangle】 线段树面积并

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4419 题目大意:给你n个矩形,每个矩形都有一种颜色,矩形覆盖会出现另外一种颜色,问你所有矩形中不同的颜 ...

  9. session生命周期

    session生命周期 原文链接:http://blog.sina.com.cn/s/blog_72c8c1150100qpgl.html 文中黄色字体为我的标记修改或添加 Session保存在服务器 ...

  10. Android课程---表格布局TableLayout

    特别注意:由于表格布局继承自线性布局,因此并不显示表格线 示例代码: <?xml version="1.0" encoding="utf-8"?> ...