Leetcode 127 Word Ladder(BFS)

题目连接:Leetcode 127 Word Ladder

解题思路:参考 Leetcode 126,将路径保存改为记录路径长度。

class Solution {
	public:
		bool trans(string a, string b) {
			bool diff = false;
			for (int i = 0; i < a.size(); i++) {
				if (a[i] != b[i] && diff) return false;
				if (a[i] != b[i]) diff = true;
			}
			return true;
		}

		int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
			wordList.push_back(beginWord);

			int n = wordList.size();
			vector<int>* graph = new vector<int>[n];
			for (int i = 0; i < n; i++) {
				for (int j = i + 1; j < n; j++) {
					if (trans(wordList[i], wordList[j])) {
						graph[i].push_back(j);
						graph[j].push_back(i);
					}
				}
			}

			int ans = 0;
			queue<int> que;
			que.push(n-1);

			int* dp = new int[n];
			for (int i = 0; i < n; i++) dp[i] = 0;
			dp[n-1] = 1;

			while (!que.empty()) {
				int start = que.front();
				que.pop(); 

				if (wordList[start] == endWord) {
					ans = dp[start];
					break;
				}

				for (int i = 0; i < graph[start].size(); i++) {
					int v = graph[start][i];
					if (dp[v] != 0) continue;
					dp[v] = dp[start] + 1;
					que.push(v);
				}
			}

			delete[] graph;
			delete[] dp;
			return ans;
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值