Careercup - Facebook面试题 - 5890898499993600

时间:2023-04-19 22:11:32

2014-05-01 02:30

题目链接

原题:

Given a matrix of letters and a word, check if the word is present in the matrix. E,g., suppose matrix is:
a b c d e f
z n a b c f
f g f a b c
and given word is fnz, it is present. However, gng is not since you would be repeating g twice.
You can move in all the directions around an element.

题目:给定一个字母矩阵,给定一个单词,请判断从矩阵某一点出发,能否走出一条路径组成这个单词。每一步可以走8邻接的方向。

解法:这基本就是Leetcode的原题Word Search,DFS搞定。如果矩阵太大的话,可以用BFS防止递归过深造成的栈溢出,不过效率方面就更慢了。

代码:

 // http://www.careercup.com/question?id=5890898499993600
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
n = (int)board.size();
if (n == ) {
return false;
}
m = (int)board[].size();
word_len = (int)word.length(); if (word_len == ) {
return true;
} int i, j;
for (i = ; i < n; ++i) {
for (j = ; j < m; ++j) {
if(dfs(board, word, i, j, )) {
return true;
}
}
}
return false;
}
private:
int n, m;
int word_len; bool dfs(vector<vector<char> > &board, string &word, int x, int y, int idx) {
static const int d[][] = {
{-, -},
{-, },
{-, +},
{ , -},
{ , +},
{+, -},
{+, },
{+, +}
}; if (x < || x > n - || y < || y > m - ) {
return false;
} if (board[x][y] < 'A' || board[x][y] != word[idx]) {
// already searched here
// letter mismatch here
return false;
} bool res;
if (idx == word_len - ) {
// reach the end of word, success
return true;
} for (int i = ; i < ; ++i) {
board[x][y] -= 'a';
res = dfs(board, word, x + d[i][], y + d[i][], idx + );
board[x][y] += 'a';
if (res) {
return true;
}
}
// all letters will be within [a-z], thus I marked a position as 'searched' by setting them to an invalid value.
// we have to restore the value when the DFS is done, so their values must still be distiguishable.
// therefore, I used an offset value of 'a'.
// this tricky way is to save the extra O(n * m) space needed as marker array. return false;
}
};