19.2.15 [LeetCode 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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

题意

矩阵中是否存在一条连续路径是所给字符串

题解

用的dfs回溯,时间效率不算很高

 1 class Solution {
 2 public:
 3     int dire[4][2] = { -1,0,1,0,0,1,0,-1 };
 4     bool found(vector<vector<char>>& board, int x, int y, string word , int i) {
 5         if (i == word.length()-1)return true;
 6         int m = board.size(), n = board[0].size();
 7         board[x][y] = -1;
 8         for (int j = 0; j < 4; j++) {
 9             int nextx = x + dire[j][0], nexty = y + dire[j][1];
10             if (nextx < m&&nextx >= 0 && nexty < n&&nexty >= 0 && word[i + 1] == board[nextx][nexty])
11                 if (found(board, nextx, nexty, word, i + 1))
12                     return true;
13         }
14         board[x][y] = word[i];
15         return false;
16     }
17     bool exist(vector<vector<char>>& board, string word) {
18         int m = board.size(), n = board[0].size();
19         for (int i = 0; i < m; i++)
20             for (int j = 0; j < n; j++)
21                 if (word[0] == board[i][j] && found(board, i, j, word, 0))
22                     return true;
23         return false;
24     }
25 };
View Code
原文地址:https://www.cnblogs.com/yalphait/p/10384765.html