Coding Interview 8.2

Source: Internet
Author: User

1. a m * n matrix a [] []. The robot moves from the upper left corner to the lower right corner and can only go right or down to output all paths.

2. If some grids in the matrix can go, some grids cannot go, And all paths are output. (A [I] [j] = 1 indicates that you can go. a [I] [j] = 0 indicates that you cannot go)

Ideas:

Typical recursive algorithms. Question 1 directly uses the idea of deep search. Question 2 adds a judgment condition on the basis of Question 1.

 

# Include <iostream> # include <vector> using namespace std; struct Point {int x; int y; Point (int I, int j): x (I ), y (j) {}}; // Question 1 void Path1 (int x, int y, int m, int n, vector <Point> & vec, int len) {if (x = m | y = n) return; Point p (x, y); vec [len ++] = p; if (x = m-1 & y = n-1) {for (int I = 0; I <vec. size (); ++ I) cout <vec [I]. x <''<vec [I]. y <endl;} else {Path1 (x, y + 1, m, n, vec, len); Path1 (x + 1, y, m, n, vec, len) ;}} // Question 2 void Path2 (int x, int y, int m, int n, vector <Point> & vec, int len, int safe [] [4]) {if (x = m | y = n | safe [x] [y] = 0) return; point p (x, y); vec [len ++] = p; if (x = m-1 & y = n-1) {for (int I = 0; I <vec. size (); ++ I) cout <vec [I]. x <''<vec [I]. y <endl;} else {Path2 (x, y + 1, m, n, vec, len, safe); Path2 (x + 1, y, m, n, vec, len, safe) ;}} void main () {int m = 3, n = 4; int x = 0, y = 0; int len = 0; point p (0, 0); vector <Point> vec (m + n-1, p); Path1 (x, y, m, n, vec, len ); int safe [] [4] = {1, 1, 1, 0}, {0, 1, 1, 1}, {0, 0, 1, 1 }}; path2 (x, y, m, n, vec, len, safe );}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.