2018年力扣高頻算法面試題2圖論

課程表【需二刷】

現在你總共有 n 門課需要選,記爲 0 到 n-1。
在選修某些課程之前需要一些先修課程。 例如,想要學習課程 0 ,你需要先完成課程 1 ,我們用一個匹配來表示他們: [0,1]
給定課程總量以及它們的先決條件,判斷是否可能完成所有課程的學習?

//廣搜
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        
        vector<vector<int> > graph(numCourses, vector<int>());
        vector<int> in(numCourses);
        
        for (auto a : prerequisites)
        {
            graph[a[1]].push_back(a[0]);  //有向圖從a[1]指向a[0]
            ++in[a[0]];   //一維數組 in 來表示每個頂點的入度
        }
        
        queue<int> q;   
        for (int i = 0; i < numCourses; ++i) 
        {
            if (in[i] == 0) q.push(i);   //入度爲0的課程,即沒有先修課程的課程
        }
        
        //將所有入度爲0的點放入隊列中,然後開始遍歷隊列,從 graph 裏遍歷其連接的點,每到達一個新節點,將其入度減一,如果此時該點入度爲0,則放入隊列末尾。直到遍歷完隊列中所有的值,若此時還有節點的入度不爲0,則說明環存在,返回 false,反之則返回 true。
        while (!q.empty())   
        {
            int t = q.front(); 
            q.pop();
            for (auto a : graph[t]) {
                --in[a];
                if (in[a] == 0) q.push(a);
            }
        }
        for (int i = 0; i < numCourses; ++i) 
        {
            if (in[i] != 0) return false;
        }
        return true;
    }
};

//深搜
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        //先建立好有向圖,然後從第一門課開始,找其可構成哪門課,暫時將當前課程標記爲已訪問,然後對新得到的課程調用 DFS 遞歸,直到出現新的課程已經訪問過了,則返回 false,沒有衝突的話返回 true,然後把標記爲已訪問的課程改爲未訪問
        
        vector<vector<int>> graph(numCourses, vector<int>()); //有向圖
        vector<int> visit(numCourses); // 記錄訪問狀態,0表示還未訪問過,1表示已經訪問了,-1 表示有衝突
        for (auto a : prerequisites) 
        {
            graph[a[1]].push_back(a[0]);
        }
        for (int i = 0; i < numCourses; ++i) 
        {
            if (!canFinishDFS(graph, visit, i)) return false;
        }
        return true;
    }
    bool canFinishDFS(vector<vector<int>>& graph, vector<int>& visit, int i) {
        if (visit[i] == -1) return false;
        if (visit[i] == 1) return true;
        visit[i] = -1;
        for (auto a : graph[i]) {
            if (!canFinishDFS(graph, visit, a)) return false;
        }
        visit[i] = 1;
        return true;
    }
};

課程表II【需二刷】

現在你總共有 n 門課需要選,記爲 0 到 n-1。
在選修某些課程之前需要一些先修課程。 例如,想要學習課程 0 ,你需要先完成課程 1 ,我們用一個匹配來表示他們: [0,1]
給定課程總量以及它們的先決條件,返回你爲了學完所有課程所安排的學習順序。
可能會有多個正確的順序,你只要返回一種就可以了。如果不可能完成所有課程,返回一個空數組。
分析:bfs或者dfs進行拓撲排序,此題正是基於之前解法的基礎上稍加修改,我們從 queue中每取出一個數組就將其存在結果中,最終若有向圖中有環,則結果中元素的個數不等於總課程數,那我們將結果清空即可。

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> res;
        vector<vector<int> > graph(numCourses, vector<int>(0));
        vector<int> in(numCourses, 0);
        
        for (auto a : prerequisites) {
            graph[a[1]].push_back(a[0]);  //有向圖從a[1]指向a[0]
            ++in[a[0]];   //一維數組 in 來表示每個頂點的入度
        }
        
        queue<int> q;
        for (int i = 0; i < numCourses; ++i) {
            if (in[i] == 0) q.push(i);
        }
        
        while (!q.empty()) {
            int t = q.front();
            res.push_back(t);
            q.pop();
            for (auto &a : graph[t]) {
                --in[a];
                if (in[a] == 0) q.push(a);
            }
        }
        if (res.size() != numCourses) res.clear();
        return res;
    }
};

島嶼數量

給定一個由 ‘1’(陸地)和 ‘0’(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。
這個題我用的廣搜,代碼如下

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int res=0;
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[0].size();j++)
            {
                if(grid[i][j]=='1')
                {
                    res++;
                    bfs(grid,i,j);
                }      
            }
        }
        return res;
    }
    //以x,y爲起點進行廣搜
    void bfs(vector<vector<char>>& grid,int x,int y)
    {      
        int xx[]={0,0,1,-1};
        int yy[]={1,-1,0,0};
        
        queue<pair<int,int> >q;
        q.push(make_pair(x,y));
        
        while(!q.empty())
        {
            pair<int,int>p=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int zx=p.first+xx[i];
                int zy=p.second+yy[i];
                if(zx<0||zx>=grid.size()||zy<0||zy>=grid[0].size()||grid[zx][zy]=='0')continue;
                grid[zx][zy]='0';
                q.push(make_pair(zx,zy));
            }
        }
    }
};

單詞接龍【需二刷】

給定兩個單詞(beginWord 和 endWord)和一個字典,找到從 beginWord 到 endWord 的最短轉換序列的長度。轉換需遵循如下規則:
每次轉換隻能改變一個字母。
轉換過程中的中間單詞必須是字典中的單詞。
說明:
如果不存在這樣的轉換序列,返回 0。
所有單詞具有相同的長度。
所有單詞只由小寫字母組成。
字典中不存在重複的單詞。
你可以假設 beginWord 和 endWord 是非空的,且二者不相同。
分析:BFS:我們需要一個隊列queue,把起始單詞排入隊列中,開始隊列的循環,取出隊首詞,然後對其每個位置上的字符,用26個字母進行替換,如果此時和結尾單詞相同了,就可以返回取出詞在哈希表中的值加一。如果替換詞在字典中存在但在哈希表中不存在,則將替換詞排入隊列中,並在哈希表中的值映射爲之前取出詞加一。如果循環完成則返回0

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
	set<string>wordset(wordList.begin(),wordList.end());
	if(!wordset.count(endWord))return 0;
	
	map<string,int>pathcnt{{{beginWord,1}}};
	queue<string>q{{beginWord}};
	
	while(!q.empty())
	{
		string word=q.front();
		q.pop();
		for(int i=0;i<word.size();i++)
		{
			string newword=word;
			for(char ch='a';ch<='z';ch++)
			{
				newword[i]=ch;
				if(wordset.count(newword)&&newword==endWord)return pathcnt[word]+1;
				if(wordset.count(newword)&&!pathcnt.count(newword))
				{
					q.push(newword);
					pathcnt[newword]=pathcnt[word]+1;
				}
			}
		}
	}
	return 0;
}

Path Sum III

You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

class Solution {
public:
    
    int helper(TreeNode* root, int sum){
        if(root == NULL)
            return 0;
        
        int cnt = 0;
        if(root->val == sum)
            cnt++;
        return cnt + helper(root->left,sum - root->val) +  helper(root->right,sum - root->val);
    }
    
    int pathSum(TreeNode* root, int sum) {
        if(root == NULL)
            return 0;
        
        return helper(root,sum) + pathSum(root->left,sum) + pathSum(root->right,sum);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章