Sei sulla pagina 1di 2

statement---You are given the maze that describes a rectangular maze.

The maze is
divided into R rows by C columns of cells. Both rows and columns are numbered
starting from 0. The character '.' represents an empty cell, the character '#'
represents a wall. Implicitly, the maze is surrounded by additional walls that are
not given in the input.

You start in the cell (0, 0) and your goal is to reach the cell (R-1, C-1). In each
step, you can move from your current cell to one of the horizontally or vertically
adjacent cells. Of course, you cannot walk into a wall.

Reaching your goal is currently impossible. Luckily for you, you are carrying a
pickaxe. The pickaxe can be used exactly once to break a wall that is horizontally
or vertically adjacent to your current cell.

Find all walls such that if you use the pickaxe to break the wall, it will be
possible to reach the cell (R-1, C-1). Return the number of such walls.

solution----
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Pickaxe{
public:
int valid(vector<string> maze,int x,int y){
int row=maze.size(); int col=maze[0].size();
if(x>=0&&x<row&&y>=0&&y<col&&maze[x][y]=='.') return 1;
else return 0;
}
int find(vector<string> maze, vector<vector<int> > &sol,int x,int y,int row,int
col){
if(x==row-1&&y==col-1) return 1;
if(valid(maze,x+1,y)&&sol[x+1][y]==0){
sol[x+1][y]=1;
if(find(maze,sol,x+1,y,row,col)) return 1;
else sol[x+1][y]=0;
}
if(valid(maze,x-1,y)&&sol[x-1][y]==0){
sol[x-1][y]=1;
if(find(maze,sol,x-1,y,row,col)) return 1;
else sol[x-1][y]=0;
}
if(valid(maze,x,y+1)&&sol[x][y+1]==0){
sol[x][y+1]=1;
if(find(maze,sol,x,y+1,row,col)) return 1;
else sol[x][y+1]=0;
}
if(valid(maze,x,y-1)&&sol[x][y-1]==0){
sol[x][y-1]=1;
if(find(maze,sol,x,y-1,row,col)) return 1;
else sol[x][y-1]=0;
}
return 0;
}
int lol(vector<string> maze){
int row=maze.size(); int col=maze[0].size();
vector<vector<int > > sol(row,vector<int>(col,0));
sol[0][0]=1;
return find(maze,sol,0,0,row,col);
}
int countWalls(vector<string> maze){
int row=maze.size();
int col=maze[0].size();
int answer=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(maze[i][j]=='#'){
maze[i][j]='.';
int a=lol(maze);
if(a){
maze[i][j]='#';
answer++;
}
if(a==0) maze[i][j]='#';
}
}
}
return answer;
}
};

Potrebbero piacerti anche