版权声明:
尊重知识产权,严厉打击非法采集。
今天我参加的有道难题编程大赛看到的题目,分享我的算法给大家:
话说你在走路上班时,经过一片种植萝卜的农田。这块田地的形状是一个矩形的网格。 field的第i个元素的第j个字符,表示田地的第i行第j列的格子里包含的萝卜的数目。 我们定义一个格子的特殊程度为它周围所有格子的萝卜个数的和; 它周围的格子包含它上下左右以及对角相邻的格子, 最多有8个,在田地的边界上的格子会少一些。如果一个格子周围没有别的格子,则它的特殊程度为0。 请返回田地中特殊程度在A和B之间的所有格子的数目(包含A,B)。
Definition
Class: NumberField
Method: countSpecialNumbers
Parameters: string[], int, int
Returns: int
Method signature: int countSpecialNumbers(string[] field, int A, int B) (be sure your method is public) Constraints
我的实现方法如下: C#
using System;
using System.Collections.Generic;
using System.Text;
namespace Field
{
/// <summary>
/// 2009.6.1 with ann by hooyes
/// </summary>
public class NumberField
{
static void Main(string[] args)
{
//Test .
string[] fieldx ={
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890",
"1234567890"};
int r = countSpecialNumbers(fieldx, 3, 18);
Console.WriteLine(r);
Console.Read();
}
/// <summary>
/// 获取第i,j格的萝卜数
/// </summary>
/// <param name="i">行</param>
/// <param name="j">列</param>
/// <param name="fieldx"></param>
/// <returns></returns>
public static int fij(int i, int j,string[] fieldx)
{
int Rvalue = 0;
if (i < 0 || j < 0)
{
return 0;
}
int y = fieldx.Length - 1; //行
int x = fieldx[0].Length - 1; //列
if ((i > y) || (j > x))
{
return 0;
}
string f = fieldx[i];
byte[] hooyesBy = System.Text.Encoding.ASCII.GetBytes(f);
char xB = (char)hooyesBy[j];
Rvalue = int.Parse(xB.ToString());
return Rvalue;
}
/// <summary>
/// 获取第i,j格的特殊度
/// </summary>
/// <param name="i">行</param>
/// <param name="j">列</param>
/// <param name="fieldx"></param>
/// <returns></returns>
public static int fsp(int i, int j, string[] fieldx)
{
int Rvalue = 0;
Rvalue = fij(i - 1, j, fieldx) + fij(i + 1, j, fieldx) + fij(i, j - 1, fieldx) + fij(i, j+1, fieldx) + fij(i - 1, j - 1, fieldx) + fij(i + 1, j + 1, fieldx) + fij(i - 1, j + 1, fieldx) + fij(i + 1, j - 1, fieldx);
return Rvalue;
}
/// <summary>
/// 返回满足特殊度在A至B之间的格子数
/// </summary>
/// <param name="field"></param>
/// <param name="A">特殊度下限</param>
/// <param name="B">特殊度上限</param>
/// <returns></returns>
public static int countSpecialNumbers(string[] field, int A, int B)
{
int Rvalue = 0;
//int i=0;
//int j=0;
int y = field.Length-1; //行
int x = field[0].Length-1 ; //列
for (int i = 0; i <=y; i++)
{
for (int j = 0; j <=x;j++)
{
int tInt = fsp(i, j, field);
if (tInt >= A && tInt <= B)
{
Rvalue++;
}
}
}
return Rvalue;
}
}
}
$ welcome to hooyes.net
[INFO] ------------------------------o-
[INFO] Author : HOOYES
[INFO] Site : https://hooyes.net
[INFO] Page : https://hooyes.net/p/radish
[INFO] Last build : 2023-07-31 09:16:20 +0000
[INFO] -0------------------------------
上一篇 Windows 配置端口转发
下一篇 关于真正的Ajax方式上传文件