【Leetcode】【Medium】word search

來源:互聯網
上載者:User

標籤:

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.

 

解題思路:

使用深度優先搜尋的方法,從二維數組中的每個點出發,向上下左右進行延伸,根據判定條件及時判斷;

 

解題步驟:

1、寫一個主函數:

  (1)獲得二維數組的行列大小;

  (2)遍曆所有二維數組元素,對每個元素作為搜尋起點,調用遞迴函式;

2、寫一個遞迴函式,參數為:二維數組(引用)、待匹配的字串(c字串形式方便)、當前運動到的座標值x和y、二維數組大小m和n;

  (1)終止判定條件:x和y無效、當前運動到的字元不是字串下一個字元;

  (2)如果已經到達匹配字串末尾,返回true

  (3)暫時將當前運動到的座標字元置換為‘\0‘,因為要做出標記,以免重複折返運動;

  (4)調用4個遞迴函式,分別運動到當前運動字元的上下左右四周,並判定;

  (5)如果4個遞迴函式都false,則換回被置換的‘\0‘,返回false;

 

代碼:

 1 class Solution { 2 public: 3      bool exist(vector<vector<char> > &board, string word) { 4         m = board.size(); 5         n = board[0].size(); 6         for(int x = 0; x < m; x++) { 7             for(int y = 0; y < n; y++) { 8                 if(isFound(board, word.c_str(), x, y)) 9                     return true;10             }11         }12         return false;13     }14     15 private:16     int m;17     int n;18     bool isFound(vector<vector<char> > &board, const char* w, int x, int y) {19         if(x < 0 || y < 0 || x >= m || y >= n || *w != board[x][y])20             return false;21         if(*(w + 1) == ‘\0‘)22             return true;23         char t = board[x][y];24         board[x][y] = ‘\0‘;25         if(isFound(board, w + 1, x - 1, y) || 26             isFound(board, w + 1, x + 1, y) || 27             isFound(board, w + 1, x, y - 1) || 28             isFound(board, w + 1, x, y + 1))29             return true; 30         board[x][y]=t;31         return false;32     }33 };

 

【Leetcode】【Medium】word search

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.