Step on the Square

Source: Internet
Author: User
step on the square

Problem Description

There is a grid matrix, and the matrix boundary is infinitely far away. Let us make the following assumptions:

A. Each step, you can only move one block from the current square and walk to an adjacent square;
C. Only go north, east and west in three directions;

Excuse me: If we allow n steps (n<=20) on the grid matrix, how many different schemes are there? 2 ways to go is considered a different scheme as long as there is a difference.

Ideas:
Recursive

Starting from (I,J), the number of steps to walk n is equal to the sum of the following three items:

Starting from (I+1,J), take the number of n-1 steps. Premise: (I+1,J) has not passed
Starting from (i,j+1), take the number of n-1 steps. Premise: (i,j+1) has not passed
Starting from (I,J-1), take the number of n-1 steps. Premise: (i,j-1) has not passed

 #include <iostream> #include <algorithm> #include <cstring> using

namespace Std;

int VISITED[30][50];
    int ways (int i, int j, int n) {if (n==0) return 1;
    VISITED[I][J] = 1;
    int num = 0;
    if (!visited[i+1][j]) num + = Ways (I+1, J, n-1);//Note Set can only be a North thing, so here is +1 if (!visited[i][j-1]) num + = ways (i, j-1, n-1);

    if (!visited[i][j+1]) num + = ways (i, j+1, n-1);
    VISITED[I][J] = 0;
return num;
    } int main () {int n;
    CIN >> N;
    memset (visited, 0, sizeof (visited));
    cout << Ways (0, N) <<endl;
return 0; }

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.