Skip to content

Instantly share code, notes, and snippets.

@hyfrey
Created October 1, 2012 05:01
Show Gist options
  • Save hyfrey/3809542 to your computer and use it in GitHub Desktop.
Save hyfrey/3809542 to your computer and use it in GitHub Desktop.
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
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.
*/
class Solution {
public:
int m;
int n;
static int dir_x[5];
static int dir_y[5];
bool dfs(vector<vector<char> > &board, const string &word, int pos, int x, int y) {
if(pos >= word.size()) {
return true;
}
for(int dir = 0; dir < 4; dir++) {
int nx = x + dir_x[dir];
int ny = y + dir_y[dir];
if(nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == word[pos]) {
char c = board[nx][ny];
board[nx][ny] = '.';
if(dfs(board, word, pos+1, nx, ny)) {
return true;
}
board[nx][ny] = c;
}
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
m = board.size();
n = board[0].size();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(board[i][j] == word[0]) {
char c = board[i][j];
board[i][j] = '.';
if (dfs(board, word, 1, i, j)) {
return true;
}
board[i][j] = c;
}
}
}
return false;
}
};
int Solution::dir_x[] = {-1, 0, 1, 0};
int Solution::dir_y[] = {0, 1, 0, -1};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment