Created
January 22, 2013 14:24
-
-
Save pdu/4594996 to your computer and use it in GitHub Desktop.
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", -> re…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define MAXN 1000 | |
| bool used[MAXN][MAXN]; | |
| int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; | |
| bool valid(int i, int j, int n, int m) { | |
| return i >= 0 && i < n && j >= 0 && j < m; | |
| } | |
| bool find(vector<vector<char> >& board, bool used[MAXN][MAXN], int n, int m, | |
| int i, int j, string& word, int kth) { | |
| if (kth == word.length()) | |
| return true; | |
| bool ret = false; | |
| for (int k = 0; k < 4; ++k) { | |
| int next_i = i + dir[k][0]; | |
| int next_j = j + dir[k][1]; | |
| if (valid(next_i, next_j, n, m) | |
| && !used[next_i][next_j] | |
| && board[next_i][next_j] == word[kth]) { | |
| used[next_i][next_j] = true; | |
| ret = find(board, used, n, m, next_i, next_j, word, kth + 1); | |
| used[next_i][next_j] = false; | |
| if (ret) | |
| break; | |
| } | |
| } | |
| return ret; | |
| } | |
| class Solution { | |
| public: | |
| bool exist(vector<vector<char> > &board, string word) { | |
| if (word.empty()) | |
| return true; | |
| int n = board.size(); | |
| int m = board[0].size(); | |
| memset(used, false, sizeof(used)); | |
| for (int i = 0; i < n; ++i) | |
| for (int j = 0; j < m; ++j) | |
| if (board[i][j] == word[0]) { | |
| used[i][j] = true; | |
| if (find(board, used, n, m, i, j, word, 1)) | |
| return true; | |
| used[i][j] = false; | |
| } | |
| return false; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment