Share the algorithm I wrote

Spent time to write down C# program to implement an algorithm. Feel great! Start to practice, a question a time.

Question is from careercup:

http://www.careercup.com/question?id=4716965625069568

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FindShortestGuard
{
class Program
{
/*
http://www.careercup.com/question?id=4716965625069568
http://www.cnblogs.com/zhuli19901106/p/3710623.html
*
* Given a 2-D matrix represents the room, obstacle and guard like the following (0 is room, B->obstacle, G-> Guard):
0 0 0
B G G
B 0 0

calculate the steps from a room to nearest Guard and set the matrix, like this
2 1 1
B G G
B 1 1
Write the algorithm, with optimal solution.
*
* using BFS, breadth first search; in detail, starting from every guard, using the BFS search.
*/
static void Main(string[] args)
{
//int[,] matrix = new int[3, 3] { { 0, 0, 0 }, { -2, -1, -1 }, { -2, 0, 0 } };

/*
int[][] matrix = new int[][]{
new int[]{ 0, 0, 0},
new int[]{ -2, -1, -1},
new int[]{-2, 0, 0}
};
m = n=3;
*/

int[][] matrix = new int[][]{
new int[]{0, 0, 0, 0},
new int[]{-2, -2, -1, -1},
new int[]{-2, -2, 0, 0},
new int[]{0, 0, 0, 0}
};
m = 4;
n = 4;

solve(matrix);

Console.WriteLine(“The result of the coding: “);

}

public static void solve(int[][] matrix) {
// -1 for guard
// -2 for blockade
// 0 for room
// > 0 for distance

int nRows = (int)matrix.Length;
if (nRows == 0) {
return;
}
int mColumns = (int)matrix[0].Length;
if (mColumns == 0) {
return;
}

int i, j;

for (i = 0; i < nRows; ++i) {
for (j = 0; j < mColumns; ++j) {
if (matrix[i][j] == -1) { // Guard: -1
doBFS(matrix, i, j);
}
}
}
}

private static int n, m;

private static bool inBound(int x, int y) {
return x >= 0 && x <= n – 1 && y >= 0 && y <= m – 1;
}

private bool inBoundJulia(int x, int y){
return x>=0 && (x<=(n-1)) && (y>=0) && (y<=m-1);
}

// https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
//int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
static int[,] dd = new int[4,2]{{-1, 0}, {+1, 0}, {0, -1}, {0, +1}};

private static void doBFS(int[][] matrix, int x, int y) {
Queue<int> q = new Queue<int>();

int tmp;
int xx, yy;
int i;
int dist;

q.Enqueue(x * m + y);

while (q.Count>0) {
tmp = q.Peek();
q.Dequeue();

x = tmp / m;
y = tmp % m;

dist = matrix[x][y] > 0 ? matrix[x][y] : 0;

for (i = 0; i < 4; ++i) {
// one of 4 neighbors –
xx = x + dd[i,0];
yy = y + dd[i,1];

// boundary check – avoid duplication calculations as well
// the order is also important; in the array; and then, check node is not room;
// and then, node is already with less steps

//
if (
// node is out of boundary of matrix
!inBound(xx, yy) ||
// node is not room – secondary check
matrix[xx][yy] < 0 ||
// node visited has less steps to a guard
(matrix[xx][yy] > 0 && matrix[xx][yy] <= dist + 1))
{
// out of boundary
// a guard or a blockade
// the distance is no shorter
continue;
}

// if the node on the queue is the Guard node, (value: -1)
bool queuedNodeIsGuard = (dist == 0); //
bool queueNodeIsRoom = (dist >= 1);

if (queuedNodeIsGuard)
matrix[xx][yy] = 1;

// else if the node on the queue is a room, need to compare the distance
else if (queueNodeIsRoom )
{
// keep minimum value
bool neverCalculated = matrix[xx][yy] == 0;
bool hasHighSteps = matrix[xx][yy] > dist + 1;

bool needUpdate = (neverCalculated || hasHighSteps);
if(needUpdate)
matrix[xx][yy] = dist+1;
}

q.Enqueue(xx * m + yy);
}
}
}
}
}

时间: 2024-08-11 15:33:29

Share the algorithm I wrote的相关文章

International Macroeconomics

International MacroeconomicsContents1 Programming I: Introduction to Matlab 12 Programming II: Use of Dynare to Simulate Dynamic Models 82.1 Baseline Theoretical Example . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2 Steady Operationalizati

dpkg和perl的依赖环境出现错误故障解决(磁盘原因)

内核: uname -a Linux localhost.localdomain 3.4.29-t4 #12 Wed Mar 13 16:50:15 EST 2013 armv7l armv7l armv7l GNU/Linux dpkg安装应用时遇到问题,提示运行apt-get -f install修复依赖. apt-get -f install 后提示如下: debconf: Perl may be unconfigured (Can't locate Debconf/Log.pm in @

Yandex Algorithm 2017 Qualication Round (数组练习 + 拓扑排序练习)

Problem A. Task Management Input le: standard input Output le: standard output Time limit: 2 seconds Memory limit: 256 megabytes Sergey is Yandex junior software engineer for only several months, but he already completed n tasks. In order to manage t

Linux: the schedule algorithm in Linux kernel

Linux kernel里面用到的一个叫 CFS (Completely-Fair-Scheduler)的调度算法.在网上找的描述都很不直观,很难读.但是找到了一篇很通俗易懂的(大道至简啊...): http://people.redhat.com/mingo/cfs-scheduler/sched-design-CFS.txt 为了防止链接失效,粘贴全文如下: This is the CFS scheduler. 80% of CFS's design can be summed up in

6 Easy Steps to Learn Naive Bayes Algorithm (with code in Python)

6 Easy Steps to Learn Naive Bayes Algorithm (with code in Python) Introduction Here’s a situation you’ve got into: You are working on a classification problem and you have generated your set of hypothesis, created features and discussed the importanc

uvalive 3231 Fair Share 公平分配问题 二分+最大流 右边最多流量的结点流量尽量少。

/** 题目: uvalive 3231 Fair Share 公平分配问题 链接:https://vjudge.net/problem/UVALive-3231 题意:有m个任务,n个处理器,每个任务有两个候选处理器,只要其中一个运行,该任务就能执行. 不同任务的两个候选处理器,至少有一个不同. 求任务数最多的那个处理器所分配的任务数尽量少. 思路:二分+最大流 左边是任务,s->u,cap = 1. 如果任务u和u的候选处理器v,u->v, cap = 1. 右边是处理器,二分mi.所有处

《Algorithm Part I:Union-Find》

1.动态联通性问题描述: 有N个元素,开始时我们让每一个元素肚子构成一个集合.然后按一定的顺序将属于同一组中的元素合并,构成新的集合.其间要反复查询某个元素在哪个集合中.如下所示: 解决办法: (1)Quick-Find 声明一个长度为N的数组id,数组中元素的值代表它所属组的编号.将数组中的元素初始化为每个元素的索引值,这样就表示开始时每个元素各自构成一个独立的集合.每次union(i,j)的时候就将所有组编号等于id[i]的元素的组编号变为id[j].每次查询元素i的组编号时,返回id[i]

What does it mean for an algorithm to be fair

What does it mean for an algorithm to be fair In 2014 the White House commissioned a 90-day study that culminated in a report (pdf) on the state of “big data” and related technologies. The authors give many recommendations, including this central war

人工智能有简单的算法吗?Appendix: Is there a simple algorithm for intelligence?

In this book, we've focused on the nuts and bolts of neural networks: how they work, and how they can be used to solve pattern recognition problems. This is material with many immediate practical applications. But, of course, one reason for interest