Google算法题:仓鼠血缘

来源:互联网 发布:纵断面图绘制软件 编辑:程序博客网 时间:2024/06/03 01:14

题目


如何找到两只仓鼠的血缘关系。没有预定义任何数据结构,只是让你写一个函数来做。有能力对问题进行建模,然后快速而高质量地编码


分析


(1)构造血缘图

(2)运用dfs,看能不能找到从仓鼠a到仓鼠b的路径,有则说明有血缘,无则说明无血缘


代码


package com.graph;import java.util.*;public class Solution{int n;Set<Integer> visited = new HashSet<Integer>();Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();public boolean solve(int[][] relation, int a, int b){//Specail caseif(relation==null || relation.length==0)return false;//Build the graphn = relation.length;for(int i=0; i<n; i++){//visited.put(map)int t1 = relation[i][0];int t2 = relation[i][1];if(!map.containsKey(t1))map.put(t1, new HashSet<Integer>());map.get(t1).add(t2);if(!map.containsKey(t2))map.put(t2, new HashSet<Integer>());map.get(t2).add(t1);}//check whether the graph contains a or bif(!map.containsKey(a) || !map.containsKey(b))return false;//dfsdfs(a, b);return find==1;}int find=0;void dfs(int v, int tar){if(v==tar){find=1;return;}Set<Integer> tmpSet = map.get(v);for(int tmp:tmpSet){if(!visited.contains(tmp)){visited.add(tmp);dfs(tmp, tar);if(find==1) return;visited.remove(tmp);}}}}



原创粉丝点击