Leetcode 79: 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 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
.
1 public class Solution { 2 private int[,] directions = new int[,] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 3 4 public bool Exist(char[,] board, string word) { 5 if (word.Length == 0) return false; 6 7 int rows = board.GetLength(0), cols = board.GetLength(1); 8 var visited = new bool[rows, cols]; 9 10 for (int i = 0; i < rows; i++) 11 { 12 for (int j = 0; j < cols; j++) 13 { 14 if (board[i, j] == word[0]) 15 { 16 visited[i, j] = true; 17 if (DFS(board, word, rows, cols, i, j, 1, visited)) 18 { 19 return true; 20 } 21 visited[i, j] = false; 22 } 23 } 24 } 25 26 27 return false; 28 } 29 30 private bool DFS(char[,] board, string word, int rows, int cols, int row, int col, int start, bool[,] visited) 31 { 32 if (start >= word.Length) return true; 33 34 for (int i = 0; i < directions.GetLength(0); i++) 35 { 36 var r = row + directions[i, 0]; 37 var c = col + directions[i, 1]; 38 39 if (r >= 0 && r < rows && c >= 0 && c < cols && !visited[r, c] && board[r, c] == word[start]) 40 { 41 visited[r, c] = true; 42 if (DFS(board, word, rows, cols, r, c, start + 1, visited)) 43 { 44 return true; 45 } 46 visited[r, c] = false; 47 } 48 } 49 50 return false; 51 } 52 }