您的位置:首页 > 职场人生

Careercup - Facebook面试题 - 6685828805820416

2014-05-02 02:34 435 查看
2014-05-02 02:33

题目链接

原题:

Given the following 3 by 3 grid where the (first row, first column) is represented by (0,0):

0,1 1,2 3,3
1,1 3,3 3,2
3,0 1,3 null

we need to find if we can get to each cell in the table by following the cell locations at the current cell we are at. We can only start at cell (0,0) and follow the cell locations from that cell, to the cell it indicates and keep on doing the same for every cell.


题目:有一个3乘3的矩阵,从每个方格可以跳到其它方格,也可能无法继续跳。如果规定从(0, 0)出发,请判断能否走完所有方格?

解法:一边跳一边标记即可,其实作为任何规模的矩阵,解法都是一样:用一个counter来统计剩余的方格数,同时用O(n^2)的空间来标记每个方格是否被走到了。有时候可以想办法在原来的矩阵上做标记,避免额外的空间开销。

代码:

// http://www.careercup.com/question?id=6685828805820416 #include <cstdio>
#include <vector>
using namespace std;

struct Point {
int x;
int y;
Point(int _x = 0, int _y = 0): x(_x), y(_y) {};
};

class Solution {
public:
bool canReachAll(vector<vector<Point> > &grid) {
int n, m;

n = (int)grid.size();
if (n == 0) {
return false;
}
m = (int)grid[0].size();
if (m == 0) {
return false;
}

int cc = n * m;
Point p(0, 0);
Point next_p;

while (true) {
next_p = grid[p.x][p.y];
grid[p.x][p.y].x = n;
grid[p.x][p.y].y = m;
--cc;
p = next_p;
if (p.x < 0 && p.y < 0) {
// null terminated
break;
}
if (grid[p.x][p.y].x == n && grid[p.x][p.y].y == m) {
// already visited
break;
}
}

return cc == 0;
};
};

int main()
{
vector<vector<Point> > grid;
int n, m;
int i, j;
Solution sol;

while (scanf("%d%d", &n, &m) == 2 && (n > 0 && m > 0)) {
grid.resize(n);
for (i = 0; i < n; ++i) {
grid[i].resize(m);
}
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
scanf("%d%d", &grid[i][j].x, &grid[i][j].y);
}
}
printf(sol.canReachAll(grid) ? "Yes\n" : "No\n");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: