[leetcode] Word Search

Given a 2D board and a word, find if the word exists in the grid.

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.

https://oj.leetcode.com/problems/word-search/

 

思路:4个方向dfs,

 

public class Solution {
    public boolean exist(char[][] board, String word) {
        if (word == null || board == null || word.equals(""))
            return false;

        int m = board.length;
        int n = board[0].length;
        boolean visit[][] = new boolean[m][n];

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                boolean res = dfs(board, visit, i, j, word, 0);
                if (res)
                    return true;
            }

        return false;

    }

    private int offset[][] = new int[][] { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };

    private boolean dfs(char[][] board, boolean[][] visit, int x, int y, String word, int cur) {
        // System.out.println("dfs:"+x+","+y+","+cur);

        if (board[x][y] != word.charAt(cur))
            return false;

        if (cur == word.length() - 1) {
            return true;
        }

        int m = board.length;
        int n = board[0].length;

        visit[x][y] = true;
        int nx, ny;
        for (int i = 0; i < 4; i++) {
            nx = x + offset[i][0];
            ny = y + offset[i][1];

            if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
                boolean res = dfs(board, visit, nx, ny, word, cur + 1);
                if (res)
                    return true;
            }

        }
        visit[x][y] = false;

        return false;

    }

    public static void main(String[] args) {
        char[][] board;
        String word;
        board = new char[][] { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } };
        word = "ASA";
        System.out.println(new Solution().exist(board, word));

        board = new char[][] { { 'b' } };
        word = "b";
        System.out.println(new Solution().exist(board, word));

    }

}
View Code

 

 

第三遍记录: dfs比较经典的题目。

  注意这个dfs有返回值,每次递归的时候要先判断结果,如果已经返回true,后面就不执行了。

  注意vis[][]数组不要遗漏了和 递归时 true和false的设置时机。

  注意dfs向下递归时,先判断nx,ny的范围 和 vis数组,(有些题目可能还有其他限制条件)

  注意递归终止条件,多用小case头脑风暴测试下。

   

 

 

posted @ 2014-06-29 20:22  jdflyfly  阅读(379)  评论(0编辑  收藏  举报