每日一题之 头条笔试题

在这里插入图片描述

思路

BFS,对每个出口标记走k步能到达的点,然后记录每个点的距离。如果有某个点在之前的出口被标记走过且距离要大于当前的出口到这个点的距离的话,那么就将该点的距离更新为离当前出口最近的距离。

#include <cstdio>
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e3+7;

typedef long long ll;

struct Node
{
	int x,y,s;

		
};



int dir[4][2] = {{0,1},{-1,0},{1,0},{0,-1}};

vector<int>G[maxn];
vector<Node>A;
vector<Node>res;

bool vis[maxn][maxn];
int dist[maxn][maxn];



void bfs(int x, int y, int k, int n, int m) {
	queue<Node>q;
	Node t;
	t.x = x;
	t.y = y;
	t.s = 0;
	q.push(t);

	while(!q.empty()) {
		Node now = q.front();
		q.pop();
		
		for (int i = 0; i < 4; ++i) {
			Node tmp;
			tmp.x = now.x + dir[i][0];
			tmp.y = now.y + dir[i][1];
			tmp.s = now.s + 1;
			if (vis[tmp.x][tmp.y] && dist[tmp.x][tmp.y] > tmp.s) {
				vis[tmp.x][tmp.y] = 0;
			}
			//cout << tmp.x << " " << tmp.y << " " << endl;
			if (tmp.x >= 0 && tmp.x < n && tmp.y >= 0 && tmp.y < m && tmp.s <= k && G[tmp.x][tmp.y] == 0 &&  !vis[tmp.x][tmp.y]) {
				res.push_back(tmp);
				vis[tmp.x][tmp.y] = 1;
				dist[tmp.x][tmp.y] = tmp.s;
				q.push(tmp);
			}
		}
	} 
}


int main() {
	int k;
	cin >> k;
	char s;
	int x;
	int n = 0;
	// !cin.eof()
	//int t = 16;

	while(!cin.eof()){
		cin >> x;
		s = getchar();
		G[n].push_back(x);
		if (s == '\n') ++n;
		//G[n].push_back(x);
	}
	//int n = (int)G.size();
	int m = (int)G[0].size();
	//cout << m << endl;
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < (int)G[0].size(); ++j) {
			vis[i][j] = 0;
			dist[i][j] = maxn*maxn;
			//cout << G[i][j] << " ";
			if (G[i][j] == 1) {
				Node tmp;
				tmp.x = i;
				tmp.y = j;
				A.push_back(tmp);
				dist[i][j] = 0;
				//cout << i <<" "<< j << endl; 
			}
		}
		//cout << endl;

	}

	for (int i = 0; i < (int)A.size(); ++i) {
		//cout << A[i].x << " " << A[i].y << endl;
		bfs(A[i].x, A[i].y, k, n, m);
	}
	
	for (int i = 0; i < (int)res.size(); ++i) {
		int x = res[i].x;
		int y = res[i].y;
		G[x][y] = 0;
	}

	for (int i =  0; i < n; ++i) {
		for (int j = 0; j < m; ++j) {
			if (G[i][j] == -1 || G[i][j] == 1) cout << "0";
			else if (G[i][j] == 0 && vis[i][j] == 0) cout << "1";
			else cout << G[i][j];
			if (j != m-1) cout << ",";
			else cout << endl;  
		}
	}

	return 0;
}
/*

3
0,-1,1,0
0,0,0,-1
0,-1,0,-1
1,-1,0,0

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值