我正在尋找一種算法,可以找到網格中最大的區域。c#總結在像網格結構中的塊
,如果我有這樣的事情:
紅色塊=塊帶有衝突
我要檢查28個碰撞Objekts。
我需要一個算法,可以發現這一點:
現在我只需要檢查5個Objekts。
是否有一個簡單的C#算法呢?
我正在尋找一種算法,可以找到網格中最大的區域。c#總結在像網格結構中的塊
,如果我有這樣的事情:
紅色塊=塊帶有衝突
我要檢查28個碰撞Objekts。
我需要一個算法,可以發現這一點:
現在我只需要檢查5個Objekts。
是否有一個簡單的C#算法呢?
如果你想要的絕對最小數量的矩形,那麼我會建議this answer給你。既然你想要容易,但是,這是我的建議,這是至少有2競爭力。首先,通過逐行掃描行,找到只有一行高的矩形的最小精確覆蓋。
00000000
1 2
3 44 5
6 77 8
99999999
現在對於每一對相鄰的行依次嘗試合併它們的矩形。假設它們按水平位置排序,那麼循環看起來就像是一個排序合併。
00000000
--------
1 2
沒有合併成爲可能。
1 2
--------
3 44 5
合併1, 3
和2, 5
。
1 2
1 44 2
--------
6 77 8
合併1, 6
和4, 7
和2, 8
。
1 2
1 44 2
1 44 2
--------
99999999
沒有合併成爲可能。最終結果如下。
00000000
1 2
1 44 2
1 44 2
99999999
這裏是團結
解決using UnityEngine;
using System.Collections;
public class CollisionTileMerger:MonoBehaviour{
ArrayList rects = new ArrayList();
public int[,] rowCheck(int[,]array)
{
int y = array.GetLength(0);
int x = array.Length /y ;
int count = 1;
ArrayList rec = new ArrayList();
for(int i=0; i< y ;i++){
for(int j=0; j< x ;j++)
{
if(array[i,j] == -1)
{
array[i,j] = count;
rec.Add(i);
rec.Add(j);
}
else
{
if(rec.Count>0)
{
rects.Add (rec);
rec = new ArrayList();
count++;
}
}
}
if(rec.Count>0)
{
rects.Add (rec);
rec = new ArrayList();
count++;
}
}
return array;
}
public int[,] Merger(int[,]array)
{
int y = array.GetLength(0);
int x = array.Length /y ;
int[,] coppy = (int[,])array.Clone();
for (int i=0; i< y-1; i++)
{
int row = i;
for (int j=0; j< x; j++)
{
if(coppy[row,j]>0&&coppy[row+1,j]>0)
{
if(j==0)
{
coppy[row+1,j] = coppy[row,j];
}
else
{
if((coppy[row,j-1]>0&&coppy[row+1,j-1]>0)||(coppy[row,j-1]==0&&coppy[row+1,j-1]==0))
{
coppy[row+1,j] = coppy[row,j];
if(j==x-1)
{
//letzte Zeile
//speichern
array = (int[,])coppy.Clone();
}
}
else
{
//zurücksetzen
coppy = (int[,])array.Clone();
}
}
}
else if(coppy[row,j]==0&&coppy[row+1,j]==0)
{
//speichern
array = (int[,])coppy.Clone();
}
else
{
//zurücksetzen
coppy = (int[,])array.Clone();
}
}
}
//speichern
array = (int[,])coppy.Clone();
return array;
}
// Use this for initialization
void Start() {
int[,] a = new int[,] {
{-1,-1,-1,-1,-1,-1,-1,-1},
{-1, 0, 0, 0, 0, 0, 0,-1},
{-1, 0, 0, -1, 0, 0, 0,-1},
{-1, 0, 0, -1, 0, 0, 0,-1},
{-1, 0, 0, -1, 0, 0, 0,-1},
{-1, 0, 0,-1,-1, 0, 0,-1},
{-1, 0, 0,-1,-1, 0, 0,-1},
{-1, 0, 0,-1,-1, 0, 0,-1},
{-1,-1,-1,-1,-1,-1,-1,-1}};
displayArray (Merger(rowCheck (a)));
}
// Update is called once per frame
void Update() {
}
public void displayArray(int[,]array)
{
int y = array.GetLength(0);
int x = array.Length /y ;
string row="";
for (int i = 0; i< y; i++)
{
for(int j = 0; j<x;j++)
{
row+= array[i,j]+" ";
}
row+= "\r\n";
}
Debug.Log(row);
/*foreach(int a in array)
{
Debug.Log(array.GetLength(0));
Debug.Log(array.Length);
}*/
}
}
謝謝,我嘗試 – user2304379 2014-09-14 18:36:25