Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 18, 2017 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/906c9f719feb01ca44ed0c10a9a3aad0 to your computer and use it in GitHub Desktop.
Save jianminchen/906c9f719feb01ca44ed0c10a9a3aad0 to your computer and use it in GitHub Desktop.
Maze algorithm - using queue
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MazeProject
{
/// <summary>
/// code review - July 18, 2017
/// Maze -
/// Given an array, there is only one item is value of 9, all others are 0 or 1.
/// 0 stands for the exit is not availabe, 1 is ok to continue. Make a judgement
/// if starting from (0,0), 4 directions: upper, down, left and right, and see
/// if there is path to find 9.
/// </summary>
class Program
{
static void Main(string[] args)
{
var maze = new int[3][]{
new int[]{1, 0, 0, 1},
new int[]{1, 1, 1, 1},
new int[]{1, 0, 0, 9}};
printMatrix(maze);
Console.WriteLine(checkMaze(maze));
}
static int[][] directions = new int[4][]{
new int[]{ 1, 0},
new int[]{-1, 0},
new int[]{ 0, 1},
new int[]{ 0, -1}};
public static int checkMaze(int[][] maze)
{
if (maze == null || maze.Length == 0 || maze[0][0] == 0)
{
return 0;
}
if (maze[0][0] == 9)
{
return 1;
}
int rows = maze.Length;
int columns = maze[0].Length;
var queue = new Queue<int[]>();
queue.Enqueue(new int[] { 0, 0 });
maze[0][0] = 0;
while (queue.Count > 0)
{
var visit = queue.Dequeue();
for (int k = 0; k < 4; k++)
{
int x = visit[0] + directions[k][0];
int y = visit[1] + directions[k][1];
if (x >= 0 && x < rows && y >= 0 && y < columns)
{
if (maze[x][y] == 9)
{
return 1;
}
else if (maze[x][y] == 1)
{
queue.Enqueue(new int[] { x, y });
maze[x][y] = 0;
}
}
}
}
return 0;
}
public static void printMatrix(int[][] matrix)
{
int m = matrix.Length;
int n = matrix[0].Length;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.WriteLine(matrix[i][j] + " ");
}
Console.WriteLine("");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment