79. 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.

---

太可怕了

---

public class Solution {
    public boolean exist(char[][] board, String word) {
        // Start typing your Java solution below
        // DO NOT write main() function
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0))
                    if (helper(board, i, j, word.substring(1)))
                        return true;
            }
        }
        return false;
    }

    public boolean helper(char[][] board, int r, int c, String word) {
        if (word.length() == 0)
            return true;
        // Up
        if (r > 0 && board[r - 1][c] == word.charAt(0)) {
            char ch = board[r][c];
            board[r][c] = '#';
            if (helper(board, r - 1, c, word.substring(1)))
                return true;
            board[r][c] = ch;
        }
        // Right
        if (c < board[0].length - 1 && board[r][c + 1] == word.charAt(0)) {
            char ch = board[r][c];
            board[r][c] = '#';
            if (helper(board, r, c + 1, word.substring(1)))
                return true;
            board[r][c] = ch;
        }
        // Down
        if (r < board.length - 1 && board[r + 1][c] == word.charAt(0)) {
            char ch = board[r][c];
            board[r][c] = '#';
            if (helper(board, r + 1, c, word.substring(1)))
                return true;
            board[r][c] = ch;
        }
        // Left
        if (c > 0 && board[r][c - 1] == word.charAt(0)) {
            char ch = board[r][c];
            board[r][c] = '#';
            if (helper(board, r, c - 1, word.substring(1)))
                return true;
            board[r][c] = ch;
        }

        return false;
    }
}

 

posted @ 2013-09-15 07:57  LEDYC  阅读(186)  评论(0)    收藏  举报