Scribbling

[C++] find, deque, bfs, structured binding 본문

Computer Science/C++

[C++] find, deque, bfs, structured binding

focalpoint 2023. 9. 30. 03:22

https://leetcode.com/problems/minimum-genetic-mutation/description/?envType=study-plan-v2&envId=top-interview-150 

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

class Solution {
public:
	int minMutation(string startGene, string endGene, vector<string>& bank) {
		if (bank.empty() || find(bank.begin(), bank.end(), endGene) == bank.end()) {
			return -1;
		}
		vector<string> genes{ bank };
		genes.push_back(startGene);
		genes.push_back(endGene);

		vector<vector<int>> graph(genes.size(), vector<int>());
		for (int i = 0; i < genes.size(); i++) {
			for (int j = 0; j < genes.size(); j++) {
				int delta = 0;
				for (int k = 0; k < 8; k++) {
					if (genes[i][k] != genes[j][k]) {
						delta++;
					}
				}
				if (delta == 1) {
					graph[i].push_back(j);
				}
			}
		}

		deque<pair<string, int>> q;
		q.push_back({ startGene, 0 });
		unordered_set<string> visited;
		visited.insert(startGene);
		while (!q.empty()) {
			auto [cur, t] = q.front();
			q.pop_front();
			if (cur == endGene) {
				return t;
			}
			int i = find(genes.begin(), genes.end(), cur) - genes.begin();
			for (int j : graph[i]) {
				if (visited.count(genes[j]) == 0) {
					q.push_back({ genes[j], t + 1 });
					visited.insert(genes[j]);
				}
			}
		}
		return -1;
	}
};

'Computer Science > C++' 카테고리의 다른 글

[C++] Deque<int>  (0) 2024.02.06
[C++] 전문가를 위한 C++ - Chapter 8  (0) 2023.10.07
[C++] Smart pointers  (0) 2023.09.30
[C++] 전문가를 위한 C++ - Chapter 2  (1) 2023.09.21
[C++] 2d DP table with vector  (0) 2023.09.19