码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Word Search 解题报告

时间:2014-11-24 20:56:08      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:dfs   回溯   字符串匹配   

【题目】

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.


【解析】

DFS;回溯;递归。

public class Solution {
    char[][] board;
    int m, n;
    
    public boolean exist(char[][] board, String word) {
        if (board == null || word == null) return false;
        if (("").equals(word)) return true;
        
        this.board = board;
        m = board.length;
        n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word.charAt(0)) {
                    char tmp = board[i][j];
                    board[i][j] = '#';
                    if (dfs(i, j, word.substring(1))) return true;
                    board[i][j] = tmp;
                }
            }
        }
        return false;
    }
    
    public boolean dfs(int i, int j,  String word) {
        if (("").equals(word)) return true;
        char tar = word.charAt(0);
        String left = word.substring(1);
        if (i > 0 && board[i - 1][j] == tar) {
            board[i - 1][j] = '#';
            if (dfs(i - 1, j, left)) return true;
            board[i - 1][j] = tar;
        }
        if (j > 0 && board[i][j - 1] == tar) {
            board[i][j - 1] = '#';
            if (dfs(i, j - 1,left)) return true;
            board[i][j - 1] = tar;
        }
        if (i < m - 1 && board[i + 1][j] == tar) {
            board[i + 1][j] = '#';
            if (dfs(i + 1, j, left)) return true;
            board[i + 1][j] = tar;
        }
        if (j < n - 1 && board[i][j + 1] == tar) {
            board[i][j + 1] = '#';
            if (dfs(i, j + 1, left)) return true;
            board[i][j + 1] = tar;
        }
        return false;
    }
}


【LeetCode】Word Search 解题报告

标签:dfs   回溯   字符串匹配   

原文地址:http://blog.csdn.net/ljiabin/article/details/41450549

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!