中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
为什么图的那题不是O(V )呢?如有加了visited,应该都只会被访问一次啊
- public class Inequality {
- static class Pair {
- char large;
- char small;
- public Pair(char a , char b) {
- large = a;
- small = b;
- }
- }
- public static int hasInequalityRelationship(Pair[] pairs, char a, char b) throws Exception {
- if (pairs == null || pairs.length == 0) {
- return 0;
- }
- if (a == b) {
- return 0;
- }
- HashMap<Character, Set<Character>> map = new HashMap<Character, Set<Character>>();
- for (Pair pair : pairs) {
- if (!map.containsKey(pair.large)) {
- map.put(pair.large, new HashSet<Character>());
- }
- map.get(pair.large).add(pair.small);
- }
- boolean val1 = dfs(map, a, b, new HashSet<Character>());
- boolean val2 = dfs(map, b, a, new HashSet<Character>());
- if (val1) {
- return 1;
- } else if (val2) {
- return -1;
- } else {
- return 0;
- }
- }
- private static boolean dfs(HashMap<Character, Set<Character>> map, char a, char b, HashSet<Character> visited) throws Exception {
- if (a == b) {
- return true;
- }
- if (visited.contains(a)) {
- throw new Exception("Has Loop");
- }
- if (!map.containsKey(a)) {
- return false;
- }
- visited.add(a);
- for (char c : map.get(a)) {
- if (dfs(map, c, b, visited)) {
- return true;
- }
- }
- return false;
- }
-
- public static void main(String[] args) throws Exception {
- Pair[] pairs = {new Pair('a', 'b'), new Pair('f', 'c'), new Pair('b', 'e')};
- System.out.println(hasInequalityRelationship(pairs, 'a', 'e'));
- System.out.println(hasInequalityRelationship(pairs, 'e', 'a'));
- System.out.println(hasInequalityRelationship(pairs, 'f', 'a'));
- }
- }
复制代码
|
|