7.5总结

· · 闲话

T1 P1162 填涂颜色

广搜题。

思路:在(0,0)bfs,就可以把不在圈内的标记,最后把未标记与a[ i ][ j ] != 1 的变成2,最后输出。

简单!

Code:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=30+10;
int n,a[N][N],v[N][N];
int fx[]={0,0,1,0,-1};
int fy[]={0,1,0,-1,0};
struct node{
    int x,y;
};
queue<node>q;
void bfs(int x,int y){
    v[x][y]=0;
    a[x][y]=3;
    q.push({x,y});
    while(!q.empty()){
        node t=q.front();
        q.pop();
        for(int i=1;i<=4;i++){
            int tx=t.x+fx[i];
            int ty=t.y+fy[i];
            if(tx>=0&&tx<=n+1&&ty>=1&&ty<=n+1&&v[tx][ty]==0&&a[tx][ty]!=1){
                q.push({tx,ty});
                v[tx][ty]=1;
                a[tx][ty]=3;
            }
        }
    }
    return;
}
int main(){
    ios::sync_with_stdio(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a[i][j];
        }
    }
    bfs(0,0);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(a[i][j]==0)cout<<2;
            else if(a[i][j]==3)cout<<0;
            else cout<<a[i][j];
            cout<<' ';
        }
        cout<<'\n';
    }
    return 0;
}

T2 P1958 上学路线

太简单不放了

T3 P1238 走迷宫

思路:在(sx,sy)dfs,边走边保存路径,到(ex,ey)后输出保存的路径。

还算简单,但我在第一次写的时候把(sx,sy)写成了(1,1)。。。眼瞎 :(

这里解释一下 print 函数,此函数是一个递归函数,通过递归的方式输出答案。但是,递归是反向输出的啊。。。但是没事,嘿嘿嘿

Code:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=20+10;
int n,b[N],k,v[N][N],m,a[N][N],sx,sy,ex,ey,f;
int fx[]={0,0,-1,0,1};
int fy[]={0,-1,0,1,0};
struct node{
    int x,y;
}pre[N][N];
void print(int x,int y){
    if(x==sx&&y==sy){
        cout<<'('<<sx<<','<<sy<<')';
        return;
    }
    print(pre[x][y].x,pre[x][y].y);
    cout<<"->("<<x<<','<<y<<')';
}
void dfs(int x,int y){
    if(x==ex&&y==ey){
        print(x,y);
        cout<<'\n';
        f=1;
        return;
    }
    for(int i=1;i<=4;i++){
        int tx=x+fx[i];
        int ty=y+fy[i];
        if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&v[tx][ty]==0&&a[tx][ty]==1){
            v[tx][ty]=1;
            pre[tx][ty]={x,y};
            dfs(tx,ty);
            v[tx][ty]=0;
        }
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>a[i][j];
        }
    }
    cin>>sx>>sy>>ex>>ey;
    if(a[sx][sy]==0||a[ex][ey]==0){
        cout<<-1;
        return 0;
    }
    v[sx][sy]=1;
    dfs(sx,sy);
    if(!f){
        cout<<-1;
        return 0;
    }
    return 0;
}

:D