随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示