200. Number of Islands\127. Word Ladder

本文介绍了两种经典的图遍历算法应用案例:岛屿数量(Number of Islands)与单词阶梯(Word Ladder)。前者通过二维网格计算相连陆地形成的岛屿数量,后者在给定词典的情况下寻找两个单词间的最短转换路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

200. Number of Islands

题目描述

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.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:


11000
11000
00100
00011

Answer: 3

代码实现

法一:使用BFS计算即可:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int res = 0, m = grid.size(), n = m?grid[0].size():0;
        for(int row = 0; row < m; row++) {
            for(int col = 0; col < n; col++) {
                if(grid[row][col] == '1') {
                    res++;
                    grid[row][col] = '0';
                    queue<pair<int, int>> que;
                    que.push(make_pair(row, col));
                    while(!que.empty()) {
                        pair<int, int> tmp = que.front();
                        que.pop();
                        if(tmp.first+1 < m && grid[tmp.first+1][tmp.second] == '1') {
                            que.push(make_pair(tmp.first+1, tmp.second));
                            grid[tmp.first+1][tmp.second] = '0';
                        }  
                        if(tmp.first-1 >= 0 && grid[tmp.first-1][tmp.second] == '1') {
                            que.push(make_pair(tmp.first-1, tmp.second));
                            grid[tmp.first-1][tmp.second] = '0';
                        }
                        if(tmp.second+1 < n && grid[tmp.first][tmp.second+1] == '1') {
                            que.push(make_pair(tmp.first, tmp.second+1));
                            grid[tmp.first][tmp.second+1] = '0';
                        }
                        if(tmp.second-1 >= 0  && grid[tmp.first][tmp.second-1] == '1') {
                            que.push(make_pair(tmp.first, tmp.second-1));
                            grid[tmp.first][tmp.second-1] = '0';
                        }
                    }
                } 
            }
        }
        return res;
    }
};

127. Word Ladder

题目描述

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.

For example,

Given:

beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.

这套题目是使用BFS进行,每次把queue里面的string取出,在根据它的长度变换成别的每一种字符,把变换后的字符与目标进行匹配。若是匹配上再放回到栈中。目前这个代码实现的时候会超时。

代码实现

法一:BFS

class Solution {
public:
    bool isInWordList(vector<string> &wordList, string str) {
        for(int i = wordList.size() - 1; i >= 0; i--) 
            if(wordList[i] == str)
                return true;
        return false;        
    }

    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int sz = beginWord.size(), res = 0;
        queue<string> que;
        que.push(beginWord);
        string str;
        int wl = wordList.size();
        sort(wordList.begin(), wordList.end());
        while(!que.empty()) {
            if(res > wl) break;
            res++;
            int queue_size = que.size();
            for(int k = 0; k < queue_size; k++) {
                for(int i = 0; i < sz; i++) {
                    str = que.front();
                    string str2 = str;
                    for(char j = 'a'; j <= 'z'; j++) {
                        if(str[i] != j) {
                            str[i] = j;
                            if(isInWordList(wordList, str)) {
                                if(str == endWord)
                                    return res+1;
                                que.push(str);    
                            }
                        }
                    }
                }    
                que.pop();
            }    
            //cout << " in the loop  " << endl;
        }    

        return 0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值