Given an MxN maze, find a path from top left corner to bottom right corner. You can only move to right and down.
Let 1 denote the places we can go and 0 denotes places, which can't be visited.
Solution:
Output:
original matrix
1 0 0 1 1 0
1 1 1 0 1 0
1 1 0 1 0 1
0 1 1 0 1 0
0 1 1 1 1 1
--------------------
solution matrix
1 0 0 0 0 0
1 0 0 0 0 0
1 1 0 0 0 0
0 1 0 0 0 0
0 1 1 1 1 1
--------------------
Let 1 denote the places we can go and 0 denotes places, which can't be visited.
Solution:
#include <iostream> using namespace std; bool solveMaze(int *M, int m, int n, int i, int j, int *sol) { if(i==m-1 && j==n-1 && *(M+i*n+j)==1) { *(sol+i*n+j) = 1; return true; } if(i<m && j<n && *(M+i*n+j)==1) { if(solveMaze(M, m, n, i+1, j, sol)) { *(sol+i*n+j) = 1; return true; } if(solveMaze(M, m, n, i, j+1, sol)) { *(sol+i*n+j) = 1; return true; } *(sol+i*n+j) = 0;//sol[i][j] = 0; } return false; } void printMatrix(int *M, int m, int n) { for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cout << *(M+i*n+j) << " "; } cout << endl; } cout << "--------------------"<<endl; } int main() { int A[5][6] = { 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1 }; int S[5][6] = {0}; solveMaze(*A, 5, 6, 0, 0, *S); cout << "original matrix" << endl; printMatrix(*A, 5, 6); cout << "solution matrix" << endl; printMatrix(*S, 5, 6); return 0; }
Output:
original matrix
1 0 0 1 1 0
1 1 1 0 1 0
1 1 0 1 0 1
0 1 1 0 1 0
0 1 1 1 1 1
--------------------
solution matrix
1 0 0 0 0 0
1 0 0 0 0 0
1 1 0 0 0 0
0 1 0 0 0 0
0 1 1 1 1 1
--------------------
No comments :
Post a Comment