标签:leetcode
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
原文地址:http://7371901.blog.51cto.com/7361901/1599013