LeetCode随笔之DFS深度优先搜索
2017-08-24 21:50
465 查看
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
思路:如代码,从海边所有的点出发,大西洋能到的地方记为1,太平洋能到的地方记为2。dfs一下即可
代码:
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
加入一点dfs的理解。
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.
Example 1:
Input: [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
思路:如代码,从海边所有的点出发,大西洋能到的地方记为1,太平洋能到的地方记为2。dfs一下即可
代码:
class Solution { public: vector<pair<int,int>> res; vector<vector<int>> visit; vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) { if(matrix.empty()) return res; int m=matrix.size(); int n=matrix[0].size(); visit.resize(m,vector<int> (n,0)); for(int i=0;i<m;i++){ dfs(matrix,i,0,INT_MIN,1); dfs(matrix,i,n-1,INT_MIN,2); } for(int i=0;i<n;i++){ dfs(matrix,0,i,INT_MIN,1); dfs(matrix,m-1,i,INT_MIN,2); } return res; } void dfs(vector<vector<int>> &matrix,int x,int y,int pre,int val){ if( x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()||matrix[x][y]<pre||visit[x][y]==3||(visit[x][y]&val)==val) return; visit[x][y] |= val; if(3==visit[x][y]) res.push_back(make_pair(x,y)); dfs(matrix,x+1,y,matrix[x][y],visit[x][y]);dfs(matrix,x-1,y,matrix[x][y],visit[x][y]); dfs(matrix,x,y+1,matrix[x][y],visit[x][y]);dfs(matrix,x,y-1,matrix[x][y],visit[x][y]); } };
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
class Solution { public: vector<string> letter; string tmp; vector<string> letterCombinations(string digits) { letter.push_back(""); letter.push_back("abc");letter.push_back("def"); letter.push_back("ghi");letter.push_back("jkl"); letter.push_back("mno");letter.push_back("pqrs"); letter.push_back("tuv");letter.push_back("wxyz"); int n=digits.size(); vector<string> res; if(digits.size()==0)return res; get(letter,res,digits,tmp,0); return res; } void get(vector<string> letter,vector<string> &res,string digits,string tmp,int n){ if(n==digits.size()){ res.push_back(tmp); return; } int number=(int)(digits -'0'); for(int i=0;i<letter[number-1].size();i++){ string pretmp=tmp; pretmp+=letter[number-1][i]; get(letter,res,digits,pretmp,n+1); } } };
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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
const int dir[4][2]={0,1,0,-1,1,0,-1,0}; class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m=board.size();int n=board[0].size(); if (board.size() == 0) return false; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(word[0]==board[i][j]){ vector<vector<bool>> book(m,vector<bool> (n)); book[i][j]=1; if( findWord(board,word,i,j,book,1)) return true; } } } return false; } bool findWord(vector<vector<char>>& board,string word,int x,int y,vector<vector<bool>>& book,int idx){ if(idx==word.size())//actually, when word.size()=2,idx=2,return true; {return true;} for(int i=0;i<4;i++){ int nx=x+dir[i][0],ny=y+dir[i][1]; if(nx<0 || nx>=board.size() || ny<0 || ny>=board[0].size() || book[nx][ny]==1)continue; if(board[nx][ny]==word[idx]){ book[nx][ny]=1; //可以完全不用这个,改用如果board[nx][ny]==word[idx]的话,把board //当前的值改成“*”,下面回溯时再改回来,就可以避免过多申请内存。 if(findWord(board,word,nx,ny,book,idx+1)) return true; book[nx][ny]=0; } } return false; } };
加入一点dfs的理解。
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.
Example 1:
Input: [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
class Solution { public: bool makesquare(vector<int>& nums) { int n=nums.size(),sum=0; for(int i=0;i<n;i++){ sum+=nums[i]; } if(n==0)return false; if(sum%4!=0)return false; int meanV=sum/4; int he=0; vector<bool> book(n); bool res=true; for(int i=0;i<4;i++){ res=res && canMake(nums,book,he,meanV); } return res; } //这个是也是把备选数组从头到尾搜一遍,只不过是挑出部分放到一个篮子里。注意return的用法。 bool canMake(vector<int> &nums,vector<bool> &book,int &he,int meanV){ if(he==meanV){ return true; } if(he>meanV)return false; for(int i=0;i<nums.size();i++){ if(!book[i])book[i]=true; else continue; he+=nums[i]; bool a=canMake(nums,book,he,meanV); he-=nums[i]; if(a){ book[i]=true; return true; } else book[i]=false; } return false; } };
//这是把所有备选数挑出来放到不同篮子里!每一次循环篮子。 class Solution { bool dfs(vector<int> &sidesLength,const vector<int> &matches, int index) { if (index == matches.size()) return sidesLength[0] == sidesLength[1] && sidesLength[1] == sidesLength[2] && sidesLength[2] == sidesLength[3]; for (int i = 0; i < 4; ++i) { sidesLength[i] += matches[index]; if (dfs(sidesLength, matches, index + 1)) return true; sidesLength[i] -= matches[index]; } return false; } public: bool makesquare(vector<int>& nums) { if (nums.empty()) return false; vector<int> sidesLength(4, 0); return dfs(sidesLength, nums, 0); } };
相关文章推荐
- leetcode 124. Binary Tree Maximum Path Sum 最大路径和 + DFS深度优先搜索
- leetcode 139. Word Break 深度优先遍历DFS按照index递归搜索 + 很棒的动态规划DP做法
- leetcode 226. Invert Binary Tree 反转二叉树 + DFS深度优先搜索
- leetcode 98. Validate Binary Search Tree DFS深度优先搜索 + 两个递归函数 + 一个错误做法
- leetcode 37. Sudoku Solver 一个经典的DFS深度优先搜索的做法
- leetcode 698. Partition to K Equal Sum Subsets K个相等子集 + 深度优先搜索DFS
- Leetcode 78. Subsets Python DFS 深度优先搜索解法
- leetcode 79. Word Search DFS 单词搜索 + 深度优先遍历
- leetcode 45. Jump Game II 贪心算法&&DFS深度优先搜索
- [LeetCode] Binary Tree Postorder Traversal dfs,深度搜索
- leetcode 404. Sum of Left Leaves 所有左孩子叶节点之和计算 + 深度优先遍历DFS
- 深度优先搜索DFS(邻接表实现)
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- 深度优先搜索DFS
- HDU/HDOJ 1241 Oil Deposits (DFS)深度优先搜索
- leetcode 282. Expression Add Operators 任意添加运算符计算结果 +深度优先遍历DFS
- 深度优先搜索 DFS 算法摘记
- 深度优先搜索 dfs Oil Deposits HDU - 1241
- poj1088 滑雪 dp记忆化搜索 dfs深度优先搜索
- 深度优先搜索DFS/广度优先搜索BFS的一个应用实例(华为编程大赛赛题)