菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
22
0

Word Search

原创
05/13 14:22
阅读数 34185

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。

先找到一个等于word[0]的坐标作为开始点,然后以这个点开始往四周开始查找。用visited数组记录是否访问过某个点,避免循环访问。

代码:

 1     bool exist(int x, int y, string word, int index, vector<vector<bool> > &visited, vector<vector<char> > &board){
 2         if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size())
 3             return false;
 4         if(board[x][y] != word[index] || visited[x][y])
 5             return false;
 6         if(index == word.length()-1)
 7             return true;
 8         visited[x][y] = true;
 9         bool result = exist(x-1, y, word, index+1, visited, board) 
10                    || exist(x+1, y, word, index+1, visited, board)
11                    || exist(x, y-1, word, index+1, visited, board)
12                    || exist(x, y+1, word, index+1, visited, board);
13         visited[x][y] = false;
14         return result;
15     }
16     bool exist(vector<vector<char> > &board, string word) {
17         // IMPORTANT: Please reset any member data you declared, as
18         // the same Solution instance will be reused for each test case.
19         int l = word.length();
20         if(l == 0)
21             return true;
22         int m = board.size();
23         if(m == 0)
24             return false;
25         int n = board[0].size();
26         if(n == 0)
27             return false;
28         vector<vector<bool> > visited(m, vector<bool>(n, false));
29         for(int i = 0; i < m; i++){
30             for(int j = 0; j < n; j++){
31                 if(board[i][j] == word[0] && exist(i, j, word, 0, visited, board)){
32                     return true;
33                 }
34             }
35         }
36         return false;
37     }

 

 

发表评论

0/200
22 点赞
0 评论
收藏