Google Interview Question for SDE-3s


Country: United States




Comment hidden because of low score. Click to expand.
1
of 1 vote

BFS.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

void SecurityCheck(vector<vector<int>> &m)
{
	queue<pair<int, int>> q1, q2;
	auto parents = &q1;
	auto children = &q2;
	for (int r = 0; r < m.size(); ++r) {
		for (int c = 0; c < m[r].size(); ++c) {
			if (m[r][c] == 'G') {
				parents->push(pair<int, int>(r, c));
			}
		}
	}
	int level = 256;
	while (!parents->empty()) {
		while (!parents->empty()) {
			auto room = parents->front();
			parents->pop();
			int r = room.first;
			int c = room.second;
			if (r >= 0 &&
				r < m.size() &&
				c >= 0 &&
				c < m[r].size() &&
				(m[r][c] == '.' || m[r][c] == 'G'))
			{
				if (m[r][c] == '.') {
					m[r][c] = level;
				}
				children->push(pair<int, int>(r + 1, c));
				children->push(pair<int, int>(r - 1, c));
				children->push(pair<int, int>(r, c + 1));
				children->push(pair<int, int>(r, c - 1));
			}
		}
		++level;
		swap(parents, children);
	}
}

void Print(vector<vector<int>> const &m)
{
	for (auto r : m) {
		for (int n : r) {
			if (n < 256) {
				cout << static_cast<char>(n);
			} else {
				cout << n - 256;
			}
			cout << " ";
		}
		cout << "\n";
	}
}

int main()
{
	vector<vector<int>> m = {
		{'#', '.', '.', '.', '.'},
		{'.', '.', '#', '.', '.'},
		{'.', 'G', '.', '#', '#'},
		{'.', '#', '.', 'G', '.'},
		{'.', '.', '.', '.', '.'}
	};
	SecurityCheck(m);
	Print(m);
}

- Alex December 05, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

cost will be same as running BFS from all guards position?

- Anonymous December 05, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@anurag.iitp. Correct. It's a regular single BFS, except there are several nodes on the starting level.

- Alex December 06, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More