One: solution to the problem
There is no skill in this topic, it is to use a letter as the center, and recursively compare up, down, left, and right.
Time: O(m*n*3^k), Space: O(m*n)
It is a little strange that on leetcode, the same program, Java code can pass, but C ++ code can not pass. But it can pass perfectly on lintcode !, indicating that the leetcode test is still a bit buggy
Two: complete code examples (C ++ version and Java version)
C++:
class Solution { private: bool exist(vector<vector<char>>& board, vector<vector<bool>> visited, int i, int j, int idx, string word) { if (idx == word.length()) return true; if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || visited[i][j] || board[i][j] != word[idx]) return false; visited[i][j] = true; bool existed = exist(board,visited,i-1,j,idx+1,word)|| exist(board,visited,i+1,j,idx+1,word)|| exist(board,visited,i,j-1,idx+1,word)|| exist(board,visited,i,j+1,idx+1,word); visited[i][j] = false; return existed; } public: bool exist(vector<vector<char>>& board, string word) { if (board.size() == 0 || board[0].size() == 0) return false; int m = board.size(); int n = board[0].size(); vector<vector<bool>> visited(m,vector<bool>(n,false)); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (exist(board, visited, i, j, 0, word)) return true; return false; } };
Java:
class Solution { private boolean exist(char[][] board,boolean[][] visited,int i,int j,int idx,String word) { if(idx==word.length()) return true; if(i<0 || i>=board.length || j<0 || j>=board[0].length || visited[i][j] || board[i][j]!=word.charAt(idx)) return false; visited[i][j]=true; boolean existed=exist(board,visited,i-1,j,idx+1,word)|| exist(board,visited,i+1,j,idx+1,word)|| exist(board,visited,i,j-1,idx+1,word)|| exist(board,visited,i,j+1,idx+1,word); visited[i][j]=false; return existed; } public boolean exist(char[][] board, String word) { if(board==null || board.length==0 || board[0]==null || board[0].length==0) return false; int m=board.length; int n=board[0].length; boolean[][] visited=new boolean[m][n]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) if(exist(board,visited,i,j,0,word)) return true; return false; } }