标签:
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 =
[
[‘A‘,‘B‘,‘C‘,‘E‘],
[‘S‘,‘F‘,‘C‘,‘S‘],
[‘A‘,‘D‘,‘E‘,‘E‘]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
给出一个矩阵和一个单词,判断单词是否存在矩阵中。
单词可以用矩阵中的连续字符组合而成,这里的“连续”意味着上下左右相邻。同一个矩阵单元只能使用一次。
这道题是一个递归搜索问题,令单词长度为L,矩阵是M*N的,每个矩阵单元都可以作为搜索的起始节点,每个节点都有四个(上下左右)搜索分支,因此形成M*N个四叉搜索树,因此算法时间度是O(M*N*4L)。给出代码如下:
bool exist(vector<vector<char>>& board, string word) { int m = board.size(); if (0==m) return word.empty(); int n = board[0].size(); for (int i=0; i<m; ++i) for (int j=0; j<n; ++j) if (dfs(board, i, j, word, 0)) return true; return false; } bool dfs(vector<vector<char>>& board, int i, int j, stri { if (k == word.size()) return true; int m = board.size(); int n = board[0].size(); if (i<0 || i>=m || j<0 || j>=n) return false; char c = board[i][j]; if (c != word[k]) return false; const int px[] = {-1,1,0,0}; const int py[] = {0,0,-1,1}; board[i][j] = ‘ ‘; for (int s=0; s<4; ++s) if (dfs(board, i+px[s], j+py[s], word, k+1)) return true; board[i][j] = c; return false; }
标签:
原文地址:http://www.cnblogs.com/zhiguoxu/p/5504037.html