Careercup - Facebook面试题 - 6685828805820416

2014-05-02 02:33

题目链接

原题:

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

, , ,
, , ,
, , 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 (,) 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 = , int _y = ): x(_x), y(_y) {};
}; class Solution {
public:
bool canReachAll(vector<vector<Point> > &grid) {
int n, m; n = (int)grid.size();
if (n == ) {
return false;
}
m = (int)grid[].size();
if (m == ) {
return false;
} int cc = n * m;
Point p(, );
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 < && p.y < ) {
// null terminated
break;
}
if (grid[p.x][p.y].x == n && grid[p.x][p.y].y == m) {
// already visited
break;
}
} return cc == ;
};
}; int main()
{
vector<vector<Point> > grid;
int n, m;
int i, j;
Solution sol; while (scanf("%d%d", &n, &m) == && (n > && m > )) {
grid.resize(n);
for (i = ; i < n; ++i) {
grid[i].resize(m);
}
for (i = ; i < n; ++i) {
for (j = ; j < m; ++j) {
scanf("%d%d", &grid[i][j].x, &grid[i][j].y);
}
}
printf(sol.canReachAll(grid) ? "Yes\n" : "No\n");
} return ;
}
上一篇:jquery mobile 学习总结


下一篇:centos内核优化--转至网络