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、可以想到的是使用回溯法。

2、不能重復使用,想到用一個數組來標記每個元素的使用情況。

3、其實就是一個字符一個字符地匹配,當前字符相同,則向四周匹配。

4、從二維數組哪個字符開始匹配呢?遍歷二維數組,依次將字符當做第一個字符跟字符串開始匹配。

 

一些注意事項,見代碼中的標記。

 

class Solution { public boolean exist(char[][] board, String word) { if(board==null||board.length==0) return false; //用一個數組表示某個位置上的元素是否已經使用過
        int m=board.length; int n=board[0].length; boolean[] flag=new boolean[m*n]; //從每個位置開始遍歷看是否包含此字符串。
        for(int i=0;i<m;i++) for(int j=0;j<n;j++){ if(helper(board,word,i,j,flag,0)) return true; } return false; } public boolean helper(char[][] board,String word,int i,int j,boolean[] flag,int index){
    //當index大於Word的最后一個位置,也就是前面匹配都成功了,可以返回true。
if(index==word.length()) return true;
if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=word.charAt(index)||flag[i*board[0].length+j]) return false; //符合要求后,表示當前字符與字符串中對應字符相等,將該字符標記為使用過,再去判斷剩下的字符。 flag[i*board[0].length+j]=true; if(helper(board,word,i+1,j,flag,index+1)||helper(board,word,i-1,j,flag,index+1) ||helper(board,word,i,j-1,flag,index+1)||helper(board,word,i,j+1,flag,index+1)) return true;
      
      
       //這里是關鍵,如果后面不匹配,就得把該位置的標志清除了,然后返回進行其他位置的比對,不清除會影響結果。
//如果后面的不匹配,就得把當前的標志清除返回。 flag[i*board[0].length+j]=false; return false; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM