日08-検索Leetcode-200、127、126、473、407

例1:LeetCode200




void DFS(std::vector<std::vector<int>>& mark,
       std::vector<std::vector<char>>& grid, int x, int y) {
       mark[x][y] = 1;
       static const int dx[] = { -1, 1, 0, 0 };   // 方向数组
       static const int dy[] = { 0, 0, -1, 1 };
       for (int i = 0; i < 4; i++) {
              int newx = x + dx[i];
              int newy = y + dy[i];
              if (newx < 0 || newx >= mark.size() ||
                     newy < 0 || newy >= mark[newx].size()) {
                     continue;
              }
              if (grid[newx][newy] == '1' && mark[newx][newy] == 0) {
                     DFS(mark, grid, newx, newy);
              }
       }
}


void BFS(std::vector<std::vector<int>>& mark,
       std::vector<std::vector<char>>& grid, int x, int y) {
       static const int dx[] = { -1, 1, 0, 0 };  // 方向数组
       static const int dy[] = { 0, 0, -1, 1 };
       std::queue<std::pair<int, int>> Q;
       Q.push(std::make_pair(x, y));
       mark[x][y] = 1;
       while (!Q.empty()) {
              x = Q.front().first;
              y = Q.front().second;
              Q.pop();
              for (int i = 0; i < 4; i++) {
                     int newx = dx[i] + x;
                     int newy = dy[i] + y;
                     if (newx < 0 || newx >= mark.size() ||
                           newy < 0 || newy >= mark[newx].size()) {
                           continue;
                     }
                     if (mark[newx][newy] == 0 && grid[newx][newy] == '1') {
                           Q.push(std::make_pair(newx, newy));
                           mark[newx][newy] = 1;
                     }
              }
       }
}

/**
  Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
  An island is surrounded by water and is formed by connecting adjacent lands horizontally
  or vertically. You may assume all four edges of the grid are all surrounded by water.
 */
#include <stdio.h>
#include <vector>
#include <queue>
class Solution {
public:
       int numIslands(std::vector<std::vector<char>>& grid) {
              int island_nums = 0;
              std::vector<std::vector<int>> mark;
              for (int i = 0; i < grid.size(); i++) {
                     mark.push_back(std::vector<int>());  // push空的vector
                     for (int j = 0; j < grid[i].size(); j++) {
                           mark[i].push_back(0);
                     }
              }
              for (int i = 0; i < grid.size(); i++) {
                     for (int j = 0; j < grid[i].size(); j++) {
                           if (grid[i][j] == '1' && mark[i][j] == 0) {
                                  DFS(mark, grid, i, j);
                                  island_nums++;
                           }
                     }
              }
              return island_nums;
       }
private:
       void DFS(std::vector<std::vector<int>>& mark,
              std::vector<std::vector<char>>& grid, int x, int y) {
              mark[x][y] = 1;
              static const int dx[] = { -1, 1, 0, 0 };
              static const int dy[] = { 0, 0, -1, 1 };
              for (int i = 0; i < 4; i++) {
                     int newx = x + dx[i];
                     int newy = y + dy[i];
                     if (newx < 0 || newx >= mark.size() ||
                           newy < 0 || newy >= mark[newx].size()) {
                           continue;
                     }
                     if (grid[newx][newy] == '1' && mark[newx][newy] == 0) {
                           DFS(mark, grid, newx, newy);
                     }
              }
       }
       void BFS(std::vector<std::vector<int>>& mark,
              std::vector<std::vector<char>>& grid, int x, int y) {
              static const int dx[] = { -1, 1, 0, 0 };
              static const int dy[] = { 0, 0, -1, 1 };
              std::queue<std::pair<int, int>> Q;
              Q.push(std::make_pair(x, y));
              mark[x][y] = 1;
              while (!Q.empty()) {
                     x = Q.front().first;
                     y = Q.front().second;
                     Q.pop();
                     for (int i = 0; i < 4; i++) {
                           int newx = dx[i] + x;
                           int newy = dy[i] + y;
                           if (newx < 0 || newx >= mark.size() ||
                                  newy < 0 || newy >= mark[newx].size()) {
                                  continue;
                           }
                           if (mark[newx][newy] == 0 && grid[newx][newy] == '1') {
                                  Q.push(std::make_pair(newx, newy));
                                  mark[newx][newy] = 1;
                           }
                     }
              }
       }
};
int main() {
       std::vector<std::vector<char>> grid;
       char str[10][10] = { "11100", "11000", "00100", "00011" };
       for (int i = 0; i < 4; i++) {
              grid.push_back(std::vector<char>());
              for (int j = 0; j < 5; j++) {
                     grid[i].push_back(str[i][j]);
              }
       }
       Solution solve;
       printf("%d\n", solve.numIslands(grid));
       return 0;
}

例2:LeetCode127







/**
 Given two words (beginWord and endWord), and a dictionary's word list,
 find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
 */
#include <stdio.h>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
class Solution {
public:
       int ladderLength(std::string beginWord, std::string endWord, std::vector<std::string>& wordList) {
              std::map<std::string, std::vector<std::string>> graph;
              construct_graph(beginWord, wordList, graph);
              return BFS_graph(beginWord, endWord, graph);
       }
private:
       bool connect(const std::string& word1, const std::string& word2) {  // 判断 word1 word2 是否可以转化
              int cnt = 0;
              for (int i = 0; i < word1.length(); i++) {
                     if (word1[i] != word2[i]) {
                           cnt++;
                     }
              }
              return cnt == 1;
       }
       void construct_graph(std::string& beginWord, std::vector<std::string>& wordList,
              std::map<std::string, std::vector<std::string>>& graph) {  // 根据是否可以转化构造关系表
              wordList.push_back(beginWord);
              for (int i = 0; i < wordList.size(); i++) {
                     graph[wordList[i]] = std::vector<std::string>();
              }
              for (int i = 0; i < wordList.size(); i++) {
                     for (int j = i + 1; j < wordList.size(); j++) {  // j 从 i + 1 开始减少比较次数
                           if (connect(wordList[i], wordList[j])) {
                                  graph[wordList[i]].push_back(wordList[j]);
                                  graph[wordList[j]].push_back(wordList[i]);
                           }
                     }
              }
       }
       int BFS_graph(std::string& beginWord, std::string& endWord,
              std::map<std::string, std::vector<std::string>>& graph) {
              std::queue<std::pair<std::string, int>> Q;
              std::set<std::string> visit;
              Q.push(std::make_pair(beginWord, 1));
              visit.insert(beginWord);
              while (!Q.empty()) {
                     std::string node = Q.front().first;
                     int step = Q.front().second;
                     Q.pop();
                     if (node == endWord) {
                           return step;
                     }
                     // 类型标识符 &引用名=目标变量名。引用就是某一变量(目标)的一个别名,对引用的操作与对变量直接操作完全一样。
                     const std::vector<std::string>& neighbors = graph[node];
                     for (int i = 0; i < neighbors.size(); i++) {
                           if (visit.find(neighbors[i]) == visit.end()) {
                                  Q.push(std::make_pair(neighbors[i], step + 1));
                                  visit.insert(neighbors[i]);
                           }
                     }
              }
              return 0;
       }
};
int main() {
       std::string beginWord = "hit";
       std::string endWord = "cog";
       std::vector<std::string> wordLsit;
       wordLsit.push_back("hot");
       wordLsit.push_back("dot");
       wordLsit.push_back("dog");
       wordLsit.push_back("lot");
       wordLsit.push_back("log");
       wordLsit.push_back("cog");
       Solution solve;
       int result = solve.ladderLength(beginWord, endWord, wordLsit);
       printf("result = %d\n", result);
       return 0;
}

例3:LeetCode126




/**
 Given two words (beginWord and endWord), and a dictionary's word list,
  find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
 */
#include <stdio.h>
#include <vector>
#include <string>
#include <map>
struct Qitem {
       std::string node;
       int parent_pos;
       int step;
       Qitem(std::string _node, int _parent_pos, int _step) : node(_node), parent_pos(_parent_pos), step(_step) {}
};
class Solution {
public:
       std::vector<std::vector<std::string>> findLadders(std::string beginWord,
              std::string endWord, std::vector<std::string>& wordList) {
              std::map<std::string, std::vector<std::string>> graph;
              construct_graph(beginWord, wordList, graph);
              std::vector<Qitem> Q;
              std::vector<int> end_word_pos;
              BFS_graph(beginWord, endWord, graph, Q, end_word_pos);
              std::vector<std::vector<std::string>> result;
              for (int i = 0; i < end_word_pos.size(); i++) {
                     int pos = end_word_pos[i];
                     std::vector<std::string> path;
                     while (pos != -1) {
                           path.push_back(Q[pos].node);
                           pos = Q[pos].parent_pos;
                     }
                     result.push_back(std::vector<std::string>());
                     for (int j = path.size() - 1; j >= 0; j--) {
                           result[i].push_back(path[j]);
                     }
              }
              return result;
       }
private:
       void BFS_graph(std::string& beginWord, std::string& endWord,
              std::map<std::string, std::vector<std::string>>& graph,
              std::vector<Qitem>& Q, std::vector<int>& end_word_pos) {
              std::map<std::string, int> visit;
              int min_step = 0;
              Q.push_back(Qitem(beginWord, -1, 1));
              visit[beginWord] = 1;
              int front = 0;
              while (front != Q.size()) {
                     const std::string& node = Q[front].node;
                     int step = Q[front].step;
                     if (min_step != 0 && step > min_step) {
                           break;
                     }
                     if (node == endWord) {
                           min_step = step;
                           end_word_pos.push_back(front);
                     }
                     const std::vector<std::string>& neighbors = graph[node];
                     for (int i = 0; i < neighbors.size(); i++) {
                           if (visit.find(neighbors[i]) == visit.end() || visit[neighbors[i]] == step + 1) {
                                  Q.push_back(Qitem(neighbors[i], front, step + 1));
                                  visit[neighbors[i]] = step + 1;
                           }
                     }
                     front++;
              }
       }
       bool connect(const std::string& word1, const std::string& word2) {  // 判断 word1 word2 是否可以转化
              int cnt = 0;
              for (int i = 0; i < word1.length(); i++) {
                     if (word1[i] != word2[i]) {
                           cnt++;
                     }
              }
              return cnt == 1;
       }
       void construct_graph(std::string& beginWord, std::vector<std::string>& wordList,
              std::map<std::string, std::vector<std::string>>& graph) {
              int has_begin_word = 0;
              for (int i = 0; i < wordList.size(); i++) {
                     if (wordList[i] == beginWord) {
                           has_begin_word = 1;
                     }
                     graph[wordList[i]] = std::vector<std::string>();
              }
              for (int i = 0; i < wordList.size(); i++) {
                     for (int j = i + 1; j < wordList.size(); j++) {
                           if (connect(wordList[i], wordList[j])) {
                                  graph[wordList[i]].push_back(wordList[j]);
                                  graph[wordList[j]].push_back(wordList[i]);
                           }
                     }
                     if (has_begin_word == 0 && connect(beginWord, wordList[i])) {
                           graph[beginWord].push_back(wordList[i]);
                     }
              }
       }
};
int main() {
       std::string beginWord = "hit";
       std::string endWord = "cog";
       std::vector<std::string> wordList;
       wordList.push_back("hot");
       wordList.push_back("dot");
       wordList.push_back("dog");
       wordList.push_back("lot");
       wordList.push_back("log");
       wordList.push_back("cog");
       Solution solve;
       std::vector<std::vector<std::string>> result = solve.findLadders(beginWord, endWord, wordList);
       for (int i = 0; i < result.size(); i++) {
              for (int j = 0; j < result[i].size(); j++) {
                     printf("[%s] ", result[i][j].c_str());
              }
              printf("\n");
       }
       return 0;
} 

例4:LeetCode473




// 深度搜索算法
class Solution {
public:
       bool makesquare(std::vector<int>& nums) {
              if (nums.size() < 4) {
                     return false;
              }
              int sum = 0;
              for (int i = 0; i < nums.size(); i++) {
                     sum += nums[i];
              }
              if (sum % 4) {
                     return false;
              }
              std::sort(nums.begin(), nums.end(), cmp);  // 默认从小到大排序
              int bucket[4] = { 0 };
              return generate(0, nums, sum / 4, bucket);
       }
private:
       static bool cmp(const int& len_a, const int& len_b) {  // 必须要加static,否则会报错
              return len_a > len_b;
       }
       bool generate(int i, std::vector<int>& nums, int target, int bucket[]) {
              if (i >= nums.size()) {
                     return bucket[0] == target && bucket[1] == target
                           && bucket[2] == target && bucket[3] == target;
              }
              for (int j = 0; j < 4; j++) {
                     if (bucket[j] + nums[i] > target) {
                           continue;
                     }
                     bucket[j] += nums[i];
                     if (generate(i + 1, nums, target, bucket)) {
                           return true;
                     }
                     bucket[j] -= nums[i];
              }
              return false;
       }
};

/**
 Remember the story of Little Match Girl? By now, you know exactly what matchsticks
 the little match girl has, please find out a way you can make one square by using
 up all those matchsticks. You should not break any stick, but you can link them up,
 and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length.
Your output will either be true or false, to represent whether you could make one square
using all the matchsticks the little match girl has.
 */
#include <stdio.h>
#include <vector>
#include <algorithm>
 // // 深度搜索算法(更优解)
 // class Solution{
 // public:
 //     bool makesquare(std::vector<int> &nums){
 //         if(nums.size() < 4){
 //             return false;
 //         }
 //         int sum = 0;
 //         for(int i = 0; i < nums.size(); i++){
 //             sum += nums[i];
 //         }
 //         if(sum % 4){
 //             return false;
 //         }
 //         std::sort(nums.begin(), nums.end(), cmp);  // 默认从小到大排序
 //         int bucket[4] = {0};
 //         return generate(0, nums, sum / 4, bucket);
 //     }
 // private:
 //     static bool cmp(const int &len_a, const int &len_b){  // 必须要加static,否则会报错
 //         return len_a > len_b;
 //     }
 //     bool generate(int i, std::vector<int> &nums, int target, int bucket[]){
 //         if(i >= nums.size()){
 //             return bucket[0] == target && bucket[1] == target
 //                    && bucket[2] == target && bucket[3] == target;
 //         }
 //         for(int j = 0; j < 4; j++){
 //             if(bucket[j] + nums[i] > target){
 //                 continue;
 //             }
 //             bucket[j] += nums[i];
 //             if(generate(i + 1, nums, target, bucket)){
 //                 return true;
 //             }
 //             bucket[j] -= nums[i];
 //         }
 //         return false;
 //     }
 // };
 // 位运算方法
class Solution {
public:
       bool makesquare(std::vector<int>& nums) {
              if (nums.size() < 4) {
                     return false;
              }
              int sum = 0;
              for (int i = 0; i < nums.size(); i++) {
                     sum += nums[i];
              }
              if (sum % 4) {
                     return false;
              }
              int target = sum / 4;
              std::vector<int> ok_subset;
              std::vector<int> ok_half;
              int all = 1 << nums.size();  // 有 2 的 size 次方种取法
              for (int i = 0; i < all; i++) {
                     int sum = 0;
                     for (int j = 0; j < nums.size(); j++) {
                           if (i & (1 << j)) {
                                  sum += nums[j];
                           }
                     }
                     if (sum == target) {
                           ok_subset.push_back(i);
                     }
              }
              for (int i = 0; i < ok_subset.size(); i++) {
                     for (int j = i + 1; j < ok_subset.size(); j++) {
                           if ((ok_subset[i] & ok_subset[j]) == 0) {
                                  ok_half.push_back(ok_subset[i] | ok_subset[j]);
                           }
                     }
              }
              for (int i = 0; i < ok_half.size(); i++) {
                     for (int j = i + 1; j < ok_half.size(); j++) {
                           if ((ok_half[i] & ok_half[j]) == 0) {
                                  return true;
                           }
                     }
              }
              return false;
       }
};
int main() {
       std::vector<int> nums;
       nums.push_back(1);
       nums.push_back(1);
       nums.push_back(2);
       nums.push_back(4);
       nums.push_back(3);
       nums.push_back(2);
       nums.push_back(3);
       Solution solve;
       printf("%d\n", solve.makesquare(nums));
       return 0;
}

例5:LeetCode407







/**
 Given an m x n matrix of positive integers representing the height of
 each unit cell in a 2D elevation map, compute the volume of water it is
 able to trap after raining.
 */
 // 带优先级的广度优先搜索
#include <stdio.h>
#include <vector>
#include <queue>
struct Qitem {
       int x;
       int y;
       int h;
       Qitem(int _x, int _y, int _h) : x(_x), y(_y), h(_h) {}
};
struct cmp {
       bool operator() (const Qitem& a, const Qitem& b) {
              return a.h > b.h;  // '>' 是最小堆
       }
};
 
class Solution {
public:
       int trapRainWater(std::vector<std::vector<int>>& heightMap) {
              std::priority_queue<Qitem, std::vector<Qitem>, cmp> Q;
              if (heightMap.size() < 3 || heightMap[0].size() < 3) {
                     return 0;
              }
              int row = heightMap.size();
              int column = heightMap[0].size();
              std::vector<std::vector<int>> mark;
              for (int i = 0; i < row; i++) {
                     mark.push_back(std::vector<int>());
                     for (int j = 0; j < column; j++) {
                           mark[i].push_back(0);
                     }
              }
              for (int i = 0; i < row; i++) {
                     Q.push(Qitem(i, 0, heightMap[i][0]));
                     mark[i][0] = 1;
                     Q.push(Qitem(i, column - 1, heightMap[i][column - 1]));
                     mark[i][column - 1] = 1;
              }
              for (int i = 1; i < column - 1; i++) {
                     Q.push((Qitem(0, i, heightMap[0][i])));
                     mark[0][i] = 1;
                     Q.push((Qitem(row - 1, i, heightMap[row - 1][i])));
                     mark[row - 1][i] = 1;
              }
              static const int dx[] = { -1, 1, 0, 0 };  // 方向数组
              static const int dy[] = { 0, 0, -1, 1 };
              int result = 0;
              while (!Q.empty()) {
                     int x = Q.top().x;
                     int y = Q.top().y;
                     int h = Q.top().h;
                     Q.pop();
                     for (int i = 0; i < 4; i++) {
                           int newx = x + dx[i];
                           int newy = y + dy[i];
                           if (newx < 0 || newx >= row || newy < 0 ||
                                  newy >= column || mark[newx][newy]) {
                                  continue;
                           }
                           if (h > heightMap[newx][newy]) {
                                  result += h - heightMap[newx][newy];
                                  heightMap[newx][newy] = h;
                           }
                           Q.push(Qitem(newx, newy, heightMap[newx][newy]));
                           mark[newx][newy] = 1;
                     }
              }
              return result;
       }
};
int main() {
       int test[][10] = {
                     {1, 4, 3, 1, 3, 2},
                     {3, 2, 1, 3, 2, 4},
                     {2, 3, 3, 2, 3, 1}
       };
       std::vector<std::vector<int>> heightMap;
       for (int i = 0; i < 3; i++) {
              heightMap.push_back(std::vector<int>());
              for (int j = 0; j < 6; j++) {
                     heightMap[i].push_back(test[i][j]);
              }
       }
       Solution solve;
       printf("%d\n", solve.trapRainWater(heightMap));
       return 0;
}

おすすめ

転載: www.cnblogs.com/lihello/p/11520922.html