[LeetCode] Word Search

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.

題解:本題很顯然可以採用遞歸的思路來解,可關鍵點在於當發現word中某個字符和board中某個位置的字符相同時,接下來的路應該怎麼走,因爲有可能會存在某些方向上相鄰的字符已經被比較過,所以這裏需要一個輔助存儲用於記錄word是否走過該位置。

代碼如下:

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(board == null || board.length == 0 || board[0].length == 0)
            return false;
        
        int rows = board.length;
        int cols = board[0].length;
        boolean[][] used = new boolean[rows][cols];
        
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols ; j++){
                if(search(board, word, 0, i, j, used))
                    return true;
            }
        }
        return false;
    }
    
    private boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used){
        if(index == word.length())
            return true;
        if(i >= board.length || j >= board[0].length || i < 0 || j < 0 || used[i][j] || word.charAt(index) != board[i][j])
            return false;
        
        used[i][j] = true;
        boolean result = search(board, word, index+1, i-1, j, used)||
            search(board, word, index+1, i+1, j, used)||
            search(board, word, index+1, i, j-1, used)||
            search(board, word, index+1, i, j+1, used);
        used[i][j] = false;
        return result;
    }
}


發佈了65 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章