LeetCode随笔之DFS深度优先搜索

来源:互联网 发布:创佳39寸网络电视 编辑:程序博客网 时间:2024/05/17 13:39
  1. 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一下即可
代码:

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]);    }};
  1. 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[n]-'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);        }    }};
  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;    }};
  1. 加入一点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);    }};