2015年9月28日星期一

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 =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
Solution 1: dfs on every element of the matrix.
 public class Solution {  
   public boolean exist(char[][] board, String word) {  
     int m=board.length;  
     if (m==0) return false;  
     int n=board[0].length;  
     for (int i=0; i<m; i++)   
       for (int j=0; j<n; j++)   
         if (dfs(board,i,j,0,word)) return true;  
     return false;      
   }  
   private boolean dfs(char[][] board, int i, int j, int d, String word) {  
     if (d==word.length()) return true;  
     int m=board.length, n=board[0].length;  
     if (i>=m || i<0 || j>=n || j<0) return false;  
     if (board[i][j]=='.' || board[i][j]!=word.charAt(d)) return false;  
     boolean res=false;  
     char temp=board[i][j];  
     board[i][j]='.';  
     if (!res && dfs(board,i+1,j,d+1,word)) res=true;  
     if (!res && dfs(board,i-1,j,d+1,word)) res=true;  
     if (!res && dfs(board,i,j+1,d+1,word)) res=true;  
     if (!res && dfs(board,i,j-1,d+1,word)) res=true;  
     board[i][j]=temp;  
     return res;  
   }  
 }  

没有评论:

发表评论