Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 18, 2017 18:30
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/c1ff7aea5d0064700275ef73fe425e36 to your computer and use it in GitHub Desktop.
Save jianminchen/c1ff7aea5d0064700275ef73fe425e36 to your computer and use it in GitHub Desktop.
maze - using queue - four directions
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));
}
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();
var row = visit[0];
var col = visit[1];
if( visitNeighbor(row + 1, col, ref queue, maze ) ||
visitNeighbor(row - 1, col, ref queue, maze ) ||
visitNeighbor(row, col + 1, ref queue, maze ) ||
visitNeighbor(row, col - 1, ref queue, maze ))
{
return 1;
}
}
return 0;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
/// <param name="queue"></param>
/// <param name="maze"></param>
/// <returns></returns>
private static bool visitNeighbor(int row, int column, ref Queue<int[]> queue, int[][] maze)
{
int rows = maze.Length;
int columns = maze[0].Length;
if (row < 0 || row >= rows || column < 0 || column >= columns)
{
return false;
}
var visit = maze[row][column];
if (visit == 9)
{
return true;
}
if (visit == 1)
{
maze[row][column] = 0; // mark as visited
queue.Enqueue(new int[]{row, column});
}
return false;
}
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