Word Search, Leetcode 解题笔记

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 =

word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.


public class Solution {
    boolean[][] visited;
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        visited = new boolean[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(dfs(board, word, i, j, 0)){
                    return true;
        return false;
    public boolean dfs(char[][] board, String word, int i, int j, int n){
        if(n == word.length()){
            return true;
        if(i < 0 || i > board.length-1 || j < 0 || j > board[0].length-1){
            return false;
            return false;
        if(word.charAt(n) != board[i][j]){
            return false;
        visited[i][j] = true;
        boolean result = dfs(board, word, i+1, j, n+1) || dfs(board, word, i-1, j, n+1) || dfs(board, word, i, j+1, n+1) || dfs(board, word, i, j-1, n+1);
        visited[i][j] = false;
        return result;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s