牛客网编程基础16,18(洪水)

今天也是看约瑟夫问题被难到了(ㄒoㄒ)~~

16.无缓存交换

题目描述
请编写一个函数,函数内不使用任何临时变量,直接交换两个数的值。
给定一个int数组AB,其第零个元素和第一个元素为待交换的值,请返回交换后的数组。
测试样例:
[1,2]
返回:[2,1]

class Exchange {
public:
    vector<int> exchangeAB(vector<int> AB) {
        // write code here
        AB[1]=AB[0]^AB[1];
        AB[0]=AB[0]^AB[1];
        AB[1]=AB[0]^AB[1];
        return AB;
    }

};

18.洪水

题目描述
在一个nxm矩阵形状的城市里爆发了洪水,洪水从(0,0)的格子流到这个城市,在这个矩阵中有的格子有一些建筑,洪水只能在没有建筑的格子流动。请返回洪水流到(n - 1,m - 1)的最早时间(洪水只能从一个格子流到其相邻的格子且洪水单位时间能从一个格子流到相邻格子)。
给定一个矩阵map表示城市,其中map[i][j]表示坐标为(i,j)的格子,值为1代表该格子有建筑,0代表没有建筑。同时给定矩阵的大小n和m(n和m均小于等于100),请返回流到(n - 1,m - 1)的最早时间。保证洪水一定能流到终点。

挺像BFS的,用队列解决。

class Flood {
public:
    int floodFill(vector<vector<int> > map, int n, int m) {
        // write code here
    queue<int> path;

    if( n==0 || m==0 || map[0][0]==1 )
        return 0;
    int direction[4][2]={ {0,1},{1,0},{0,-1},{-1,0} };  //r,b,l,t
    int x,y,next_x,next_y;
    int position;

    path.push(0);
    while(!path.empty())
    {
        position=path.front();
        path.pop();
        x=position/m;   //之后存入的坐标是 next_x*m + next_y 
        y=position%m;

        if( (x+1)==n && (y+1)==m )
        { 
            return map[x][y];
        } 
        for(int i=0;i<4;i++)
        {
            next_x = x+direction[i][0];
            next_y = y+direction[i][1];
            if( next_x>=0 && next_x<n && next_y>=0 && next_y<m && map[next_x][next_y]==0 )  
            {
                path.push(next_x*m+next_y);
                map[next_x][next_y]=map[x][y]+1;    //记录时间 
            }
        }
    }
    return 0;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值