feat: add Word Search LeetCode problem (#1160)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2022-12-17 06:28:51 +04:00 committed by GitHub
parent 496e012c70
commit 50349e065e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 0 deletions

View File

@ -31,6 +31,7 @@
| 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [C](./src/53.c) | Easy |
| 62 | [Unique Paths](https://leetcode.com/problems/unique-paths/description/) | [C](./src/62.c) | Medium |
| 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C](./src/66.c) | Easy |
| 79 | [Word Search](https://leetcode.com/problems/word-search/) | [C](./src/79.c) | Medium |
| 82 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [C](./src/82.c) | Medium |
| 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | [C](./src/83.c) | Easy |
| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C](./src/94.c) | Medium |

60
leetcode/src/79.c Normal file
View File

@ -0,0 +1,60 @@
int getPointKey(int i, int j, int boardSize, int boardColSize){
return boardSize * boardColSize * i + j;
}
const int directionsSize = 4;
const int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool exitsWord(int i, int j, char** board, int boardSize, int* boardColSize, int wordIndex, char* word, int* vistedPointSet){
if (board[i][j] != word[wordIndex]){
return false;
}
if (wordIndex == strlen(word) - 1){
return true;
}
for (int k = 0; k < directionsSize; k++){
int nextI = i + directions[k][0];
int nextJ = j + directions[k][1];
if (nextI < 0 || nextI >= boardSize || nextJ < 0 || nextJ >= boardColSize[i]){
continue;
}
int key = getPointKey(nextI, nextJ, boardSize, boardColSize[i]);
if (vistedPointSet[key] == 1){
continue;
}
vistedPointSet[key] = 1;
if (exitsWord(nextI, nextJ, board, boardSize, boardColSize, wordIndex + 1, word, vistedPointSet)){
return true;
}
vistedPointSet[key] = 0;
}
return false;
}
// Use backtracking.
// Runtime: Runtime: O(n*m*4^len(word))
bool exist(char** board, int boardSize, int* boardColSize, char* word){
int* vistedPointSet = (int*) calloc(getPointKey(boardSize, boardColSize[0], boardSize, boardColSize[0]), sizeof(int));
for (int i = 0; i < boardSize; i++){
for (int j = 0; j < boardColSize[i]; j++){
int key = getPointKey(i, j, boardSize, boardColSize[i]);
vistedPointSet[key] = 1;
if (exitsWord(i, j, board, boardSize, boardColSize, 0, word, vistedPointSet)){
return true;
};
vistedPointSet[key] = 0;
}
}
return false;
}