Lintcode123 Word Search solution 題解

【題目描述】

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.

給出一個二維的字母板和一個單詞,尋找字母板網格中是否存在這個單詞。

單詞可以由按順序的相鄰單元的字母組成,其中相鄰單元指的是水平或者垂直方向相鄰。每個單元中的字母最多隻能使用一次。

【題目鏈接】

www.lintcode.com/en/problem/word-search/

【題目解析】

基本思路比較簡單:從board上每一個點出發,用depth first search (DFS)上下左右四方向搜索匹配的word。需要注意到幾點:

1、考慮board的邊界

2、cell是否已經被遍歷過(臨時轉換爲特定標識字符,比如'#',recursion返回後再重置回原來的值,這樣可以省去額外開闢二維數組visited[i][j]的空間複雜度)

3、搜索結束的標誌是k == word.length()

【參考答案】

www.jiuzhang.com/solutions/word-search/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章