首页 > 代码库 > Leetcode: Word Search

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

分析:dfs。

 1 class Solution { 2 public: 3     bool exist(vector<vector<char> > &board, string word) { 4         int n = board.size(); 5         if(n == 0) return false; 6         int m = board[0].size(); 7         if(m == 0) return false; 8         vector<vector<bool> > used(n, vector<bool>(m,false)); 9         10         for(int i = 0; i < n; i++)11             for(int j = 0; j < m; j++){12                 if(dfs(board,word,used,i,j,0))13                     return true;14             }15         return false;16     }17     bool dfs(vector<vector<char> > &board, string word, vector<vector<bool> > &used, int i, int j, int k){18         if(k == word.length()) return true;19         if(i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) return false;//first check range20         if(board[i][j] != word[k] || used[i][j]) return false;//then check this21         used[i][j] = true;22         if(dfs(board, word,used,i-1,j,k+1) || dfs(board, word, used, i+1,j,k+1) || dfs(board, word, used, i, j-1, k+1)23             || dfs(board, word, used, i, j+1, k+1))24             return true;25         used[i][j] = false;26         return false;27         28     }29 };

 

Leetcode: Word Search