C#算法解決蘿卜地問題
C#算法解決蘿卜地問題是什么呢?首先讓我們來看看題目:
話說你在走路上班時,經過一片種植蘿卜的農田。這塊田地的形狀是一個矩形的網格。
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
- field 包含1個到50個元素,含1和50。
- field的每個元素包含1個到50個字符,含1和50。
- field的每個元素包含相同的字符數。
- field的每個元素的字符均為’0’到’9’之一。
- A的范圍會在0到100之間,含0和100。
- B 的范圍會在A到100之間,含A和100。
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;
- }
- }
- }
C#算法C#算法解決蘿卜地問題就向你介紹點到這里,希望對你理解C#算法有所幫助。
【編輯推薦】