-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindBall.cs
58 lines (51 loc) · 1.73 KB
/
FindBall.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//https://leetcode.com/problems/where-will-the-ball-fall/
namespace LeetCode.Problems;
public sealed class FindBall : ProblemBase
{
[Theory]
[ClassData(typeof(FindBall))]
public override void Test(object[] data) => base.Test(data);
protected override void AddTestCases()
=> Add(it => it.Param2dArray("[[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]").ResultArray("[1,-1,-1,-1,-1]"))
.Add(it => it.Param2dArray("[[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]").ResultArray("[0,1,2,3,4,-1]"))
.Add(it => it.Param2dArray("[[-1]]").ResultArray("[-1]"));
private int[] Solution(int[][] grid)
{
var width = grid[0].Length;
var balls = Enumerable.Range(0, grid[0].Length).ToArray();
for (var y = 0; y < grid.Length; y++)
{
for (var b = 0; b < width; b++)
{
if (balls[b] == -1)
{
continue;
}
var x = balls[b];
if (grid[y][x] == 1)
{
if (x + 1 == width || grid[y][x + 1] == -1)
{
balls[b] = -1;
}
else
{
balls[b] = x + 1;
}
}
else if (grid[y][x] == -1)
{
if (x - 1 < 0 || grid[y][x - 1] == 1)
{
balls[b] = -1;
}
else
{
balls[b] = x - 1;
}
}
}
}
return balls;
}
}