亚麻卖书,每本书都有与其关联性很强的书,给一个list<string,string>
代表书和与其关联的书,输出互相关联的最大集合。例如:
三国演义 水浒传
水浒传 红楼梦
哈利波特 时间简史
三国演义,水浒传,红楼梦
the key point here is convert the input list to list of <point, neigbors> , like undirect graph
then BFS to scan the graph and calculate pints of connected graph
/**
* Created by LEI_D on 6/14/2017.
*/
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Queue;
public class BookRecomm {
class Item{
String name;
String val;
public Item(String name, String val){
this.name = name;
this.val = val;
}
}
public List<String> bookRecomm(List<Item> booklist) {
if (booklist == null || booklist.size() == 0) {
return new ArrayList<String>();
}
Map<String,List<String>> map = new HashMap<String, List<String>>();
// put undirected graph into map
for(Item item : booklist) {
List<String> neigbors = map.get(item.name);
if (neigbors == null) {
neigbors = new ArrayList<String>();
map.put(item.name,neigbors);
}
neigbors.add(item.val);
List<String> neigborsrev = map.get(item.val);
if (neigborsrev == null) {
neigborsrev = new ArrayList<String>();
map.put(item.val,neigborsrev);
}
neigborsrev.add(item.name);
}
// initial visited map
Map<String, Boolean> visited = new HashMap<String, Boolean>();
for(Map.Entry<String,List<String>> entry : map.entrySet()) {
visited.put(entry.getKey(),false);
}
//BFS to find the biggest connected points
int max = Integer.MIN_VALUE;
List<String> result = new ArrayList<String>();
Queue<String> queue = new LinkedList<String>();
List<String> cur = new ArrayList<String>();
for(Map.Entry<String,List<String>> entry : map.entrySet()) {
String bookName = entry.getKey();
//System.out.println(bookName);
if (queue.isEmpty()) {
if (cur.size() > max) {
result = new ArrayList<>(cur);
max = cur.size();
}
cur.clear();
if(!visited.get(bookName)) {
cur.add(bookName);
visited.put(bookName,true);
List<String> neis = map.get(bookName);
for(String nei : neis) {
if(!visited.get(nei)) {
queue.offer(nei);
}
}
}
}
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size;i++) {
bookName = queue.poll();
cur.add(bookName);
visited.put(bookName,true);
for(String str : map.get(bookName)) {
if (!visited.get(str)) {
queue.offer(str);
}
}
}
}
}
return result;
}
}