Bfs java solution


#1

public class Solution {
public int snakeLadder(int[][] arr1, int[][] arr2) {
LinkedList list = new LinkedList();
boolean [] nums = new boolean[101];
int [] num1 = new int[101];
int [] num2 = new int[101];
int i, j, k = 0, s, r;
for (i = 0; i < arr1.length; ++i)
{
num2[arr1[i][0]] = arr1[i][1];
}
for (i = 0; i < arr2.length; ++i)
{
num1[arr2[i][0]] = arr2[i][1];
}
if (num1[100] != 0)
{
return -1;
}
list.add(1);
nums[1] = true;
while (list.size() > 0)
{
j = list.size();
for (i = 0; i < j; ++i)
{
s = list.removeFirst();
if (s == 100)
{
return k;
}
for (r = s; r <= s + 6; ++r)
{
if (r <= 100)
{
if (num2[r] != 0)
{
if (!nums[num2[r]])
{
nums[num2[r]] = true;
list.add(num2[r]);
}
}
if (num1[r] != 0)
{
if (!nums[num1[r]])
{
nums[num1[r]] = true;
list.add(num1[r]);
}
}
else if (!nums[r])
{
list.add®;
}
nums[r] = true;
}
}
}
k++;
}
return -1;
}
}