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 }