Careercup - Facebook面试题 - 6685828805820416

3x3矩阵遍历问题
本文探讨了一个3x3矩阵的问题,从指定起点出发,根据每个方格指示的目标方格进行跳跃,判断是否能遍历整个矩阵。通过标记已访问过的方格,并使用计数器跟踪剩余未访问方格的数量,最终确定是否能完成遍历。

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)的空间来标记每个方格是否被走到了。有时候可以想办法在原来的矩阵上做标记,避免额外的空间开销。

代码:

 1 // http://www.careercup.com/question?id=6685828805820416
 2 #include <cstdio>
 3 #include <vector>
 4 using namespace std;
 5 
 6 struct Point {
 7     int x;
 8     int y;
 9     Point(int _x = 0, int _y = 0): x(_x), y(_y) {};
10 };
11 
12 class Solution {
13 public:
14     bool canReachAll(vector<vector<Point> > &grid) {
15         int n, m;
16         
17         n = (int)grid.size();
18         if (n == 0) {
19             return false;
20         }
21         m = (int)grid[0].size();
22         if (m == 0) {
23             return false;
24         }
25         
26         int cc = n * m;
27         Point p(0, 0);
28         Point next_p;
29 
30         while (true) {
31             next_p = grid[p.x][p.y];
32             grid[p.x][p.y].x = n;
33             grid[p.x][p.y].y = m;
34             --cc;
35             p = next_p;
36             if (p.x < 0 && p.y < 0) {
37                 // null terminated
38                 break;
39             }
40             if (grid[p.x][p.y].x == n && grid[p.x][p.y].y == m) {
41                 // already visited
42                 break;
43             }
44         }
45         
46         return cc == 0;
47     };
48 };
49 
50 int main()
51 {
52     vector<vector<Point> > grid;
53     int n, m;
54     int i, j;
55     Solution sol;
56     
57     while (scanf("%d%d", &n, &m) == 2 && (n > 0 && m > 0)) {
58         grid.resize(n);
59         for (i = 0; i < n; ++i) {
60             grid[i].resize(m);
61         }
62         for (i = 0; i < n; ++i) {
63             for (j = 0; j < m; ++j) {
64                 scanf("%d%d", &grid[i][j].x, &grid[i][j].y);
65             }
66         }
67         printf(sol.canReachAll(grid) ? "Yes\n" : "No\n");
68     }
69     
70     return 0;
71 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3703610.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值