首页 > 代码库 > [LeetCode]79 Word Search
[LeetCode]79 Word Search
https://oj.leetcode.com/problems/word-search/
http://blog.csdn.net/linhuanmars/article/details/24336987
public class Solution { public boolean exist(char[][] board, String word) { Map<Character, List<P>> map = buildMap(board); boolean r = visit(map, word.toCharArray(), null, 0); return r; } private boolean visit(Map<Character, List<P>> map, char[] chars, P lastp, int i) { if (i >= chars.length) return true; List<P> ps = map.get(chars[i]); if (ps == null) return false; for (P p : ps) { if (p.used) continue; if (lastp != null && !nextto(lastp, p)) continue; p.used = true; boolean r = visit(map, chars, p, i + 1); if (r) return true; p.used = false; } return false; } private Map<Character, List<P>> buildMap(char[][] b) { Map<Character, List<P>> map = new HashMap<>(); for (int i = 0 ; i < b.length ; i ++) { for (int j = 0 ; j < b[i].length ; j ++) { char c = b[i][j]; List<P> list = map.get(c); if (list == null) list = new ArrayList<>(); list.add(new P(i, j)); map.put(b[i][j], list); } } return map; } boolean nextto(P p1, P p2) { return (Math.abs(p1.x - p2.x) == 1 && p1.y == p2.y) || (Math.abs(p1.y - p2.y) == 1 && p1.x == p2.x); } private static class P { int x; int y; P(int x, int y) { this.x = x; this.y = y; } boolean used; } }
[LeetCode]79 Word Search
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。