淄博的大型網(wǎng)站建設(shè)怎樣做網(wǎng)站
矩陣中的路徑(回溯)/pair的學(xué)習(xí)
- 問題
- 分析
- 示例代碼
- pair學(xué)習(xí)
問題
來自力扣:
給定一個 m x n 二維字符網(wǎng)格 board 和一個字符串單詞 word 。如果 word 存在于網(wǎng)格中,返回 true ;否則,返回 false 。
單詞必須按照字母順序,通過相鄰的單元格內(nèi)的字母構(gòu)成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內(nèi)的字母不允許被重復(fù)使用。例如,在下面的 3×4 的矩陣中包含單詞 "ABCCED"(單詞中的字母已標出)。
示例 1:
輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
輸出:true
示例 2:
輸入:board = [["a","b"],["c","d"]], word = "abcd"
輸出:false提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 僅由大小寫英文字母組成
分析
這題型,很明顯,就是回溯。定義一個查找函數(shù),然后,遞歸調(diào)用。最近被一些別的事困擾,沒心思自己寫,偷懶直接看示例代碼了。
示例代碼
class Solution {
public:bool check(vector<vector<char>>& board, vector<vector<int>>& visited, int i, int j, string& s, int k) {if (board[i][j] != s[k]) {return false;} else if (k == s.length() - 1) {return true;}visited[i][j] = true;vector<pair<int, int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};bool result = false;for (const auto& dir: directions) {int newi = i + dir.first, newj = j + dir.second;if (newi >= 0 && newi < board.size() && newj >= 0 && newj < board[0].size()) {if (!visited[newi][newj]) {bool flag = check(board, visited, newi, newj, s, k + 1);if (flag) {result = true;break;}}}}visited[i][j] = false;return result;}bool exist(vector<vector<char>>& board, string word) {int h = board.size(), w = board[0].size();vector<vector<int>> visited(h, vector<int>(w));for (int i = 0; i < h; i++) {for (int j = 0; j < w; j++) {bool flag = check(board, visited, i, j, word, 0);if (flag) {return true;}}}return false;}
};
官方的解釋:
pair學(xué)習(xí)
代碼中有pair,這讓我回想起之前用map的時候,好像用過pair,但并不了解它。
學(xué)習(xí)內(nèi)容參考這兩篇:C++ pair的基本用法總結(jié)(整理)和老衛(wèi)帶你學(xué)—C++中map與pair的區(qū)別
pair:將2個數(shù)據(jù)組成一對數(shù)據(jù)。它是結(jié)構(gòu)體,不是類。即它是同struct定義的。
使用前需要include一個頭文件#include<utility>
模板:template<class T1,class T2> struct pair
定義和訪問(用公有函數(shù)first和sencond訪問):
pair<int, int> a= { 1,5 };pair<int, int> b( 1,5 );pair<int, int> c = make_pair(1, 5);cout << a.first <<" "<< a.second << " ";cout << b.first <<" "<< b.second << " ";cout << c.first <<" "<< c.second << " ";//結(jié)果1 5 1 5 1 5
與map的區(qū)別:map是容器,pair可以生成一個一個的pair然后放入容器map中。
同樣的,pair定義的變量,可以用其他容器如vector來存放。