Word Search

来源:互联网 发布:天下无双 源码 编辑:程序博客网 时间:2024/06/05 10:26

DFS + Back tracking:

1. 总是要抱着recursion的大腿的

2. 标记visited

3. 要还原还原!一般结构是 revision -》 recursion -》 restore


The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,

word = "ABCB", -> returns false.


public class Solution {    public boolean exist(char[][] board, String word) {        if (board == null || board.length == 0 || word.length() == 0) return false;                for (int i = 0; i < board.length; i++) {            for (int j = 0; j < board[0].length; j++) {                if (board[i][j] == word.charAt(0)) {                    boolean res = find(board, word, i, j, 0);                    if (res) {                        return true;                    }                }            }        }        return false;    }        public boolean find(char[][]board, String word, int i, int j, int start) {        if (start == word.length()) {            return true;        }        if ( i < 0 || i >= board.length           ||j < 0 || j >= board[0].length            || word.charAt(start) != board[i][j] ) {            return false;        }                board[i][j] = '*';                boolean res = (find(board, word, i+1, j, start+1) ||            find(board, word, i-1, j, start+1) ||            find(board, word, i, j+1, start+1) ||            find(board, word, i, j-1, start+1));                    board[i][j] = word.charAt(start);        return res;            }}


0 0
原创粉丝点击